欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Leetcode】223. Rectangle Area(计算两矩形覆盖总面积)

程序员文章站 2022-05-15 09:19:04
...

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

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

【Leetcode】223. Rectangle Area(计算两矩形覆盖总面积)

Example:

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45

解题思路:

左侧的最大值为left,右侧为最小值的坐标并且与left进行比较找出最大值。

同理可得top,bottom

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int left = max(A,E), right = max(min(C,G), left);
        int bottom = max(B,F), top = max(min(D,H), bottom);
        return (C-A)*(D-B) - (right-left)*(top-bottom) + (G-E)*(H-F);
    }
};

 

相关标签: 面积覆盖