美文网首页
223. Rectangle Area

223. Rectangle Area

作者: a_void | 来源:发表于2016-09-17 22:40 被阅读0次

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.

Idea: be aware of number overflow

class Solution {
public:
    void swap(int &a, int &b){
        int t = a;
        a = b;
        b = t;
    }
    int max(int a, int b){
        return a > b ? a : b;
    }
    int min(int a, int b){
        return a > b ? b : a;
    }
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        // order points
        if(A > C) swap(A, C);
        if(B > D) swap(B, D);
        if(E > G) swap(E, G);
        if(F > H) swap(F, H);
        
        //
        int sum = (C - A) * (D - B) + (G - E) * (H - F);
        int h1 = min(C, G), h2 = max(A, E);
        int v1 = min(D, H), v2 = max(B, F);
        int over = 0;
        if(h1 > h2 && v1 > v2) over = (h1 - h2) * (v1 - v2);
        return sum - over; 
    }
};

相关文章

网友评论

      本文标题:223. Rectangle Area

      本文链接:https://www.haomeiwen.com/subject/ohywettx.html