leetcode笔记:Rectangle Area

一. 题目描述

Find the total area covered by two rectilinear rectangles in a 2D plane.

Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.

Assume that the total area is never beyond the maximum possible value of int.

二. 题目分析

题目大意很简单,即计算二维平面上两个矩形的覆盖面积。两矩形通过其左下和右上的坐标进行定义。假设总面积不会超过int的最大值。

根据常用的几何知识可以很快解决这个问题。假设两个矩形分别为A, BArea(A ∪ B)表示由两个矩形加起来的覆盖面积,则有以下公式:Area(A ∪ B) = Area(A) + Area(B) - Area(A ∩ B)

三. 示例代码

// C++ 代码
class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int rectangle1 = (C - A) * (D - B); int rectangle2 = (G - E) * (H - F); // 以下是两个矩阵相交部分的上下左右坐标 int left = max(A, E), right = min(C, G), top = min(D, H), bottom = max(B, F); if (right <= left || top <= bottom) return rectangle1 + rectangle2; return rectangle1 + rectangle2 - (right - left) * (top - bottom); } };
// Python 代码
class Solution: # @param {integer} A # @param {integer} B # @param {integer} C # @param {integer} D # @param {integer} E # @param {integer} F # @param {integer} G # @param {integer} H # @return {integer} def computeArea(self, A, B, C, D, E, F, G, H): sums = (C - A) * (D - B) + (G - E) * (H - F) return sums - max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0)

四. 小结

实现算法时,需注意各下标的顺序,避免出错。

你可能感兴趣的:(LeetCode,C++,算法,rectangle,2d)