Leetcode 223 Rectangle Area

1. 问题描述

  求两个矩形并的面积。
  

2. 方法与思路

  可以先求出两个矩形的交面积,然后用两个矩形面积的和减去交面积即为矩形并面积。
  注意:虽然面积不超过int的最大值,但中间边长运算时可能超过,注意处理细节,否则容易溢出。
  

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int unionArea =0;
        long wlimit,hlimit;
        wlimit = (long)min(C,G)-(long)max(A,E);
        hlimit = min(D,H)-max(B,F); 
        if(wlimit >=0 && hlimit >= 0)
        {
            unionArea = (min(C,G)-max(A,E))* (min(D,H)-max(B,F));
        }
        else
        {
            unionArea = 0;
        }
        //printf("test:%lu\n",wlimit);  
        return (C - A)*(D - B) + (G - E)*(H - F) - unionArea;
    }
};


int main()
{
    Solution sol;
    printf("%d\n",sol.computeArea(-3,0,3,4,0,-1,9,2));

    int a[8] = {-1500000001,0,-1500000000,1,1500000000,0,1500000001,1};
    //for(int i = 0; i < 8; i ++) scanf("%d",&a[i]);

    printf("%d\n",sol.computeArea(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7]));

    return 0;
}

你可能感兴趣的:(LeetCode,几何算法,求并面积)