223. Rectangle Area

Total Accepted: 38216  Total Submissions: 126941  Difficulty: Easy

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.

Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.

Subscribe to see which companies asked this question

Hide Tags
  Math

分析:

题意为给定两个矩形的对角坐标,求解两矩形所形成的面积大小。

本题参考博客:http://blog.csdn.net/pistolove/article/details/46868363

两个矩形要么重叠,要么不重叠!

先假设存在重叠,接着计算出重叠的四个角的坐标,如果满足大小关系(见代码)则存在,就减去重叠部分的面积。

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int result=(D-B)*(C-A)+(H-F)*(G-E);
        //求取重叠部分的四个角坐标
        int left = max(A, E);  
        int down = max(B, F);  
        int right = min(G, C);  
        int up = min(D, H);  
  
        if (up <= down || right <= left) //没有重叠
            return result;  
    
        return  result - (right - left) * (up - down);
    }
};

注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51546418

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,C++,算法,面试,回溯法)