223 Rectangle Area 矩形面积

在二维平面上计算出两个由直线构成的矩形叠加覆盖后的面积。

假设面积不会超出int的范围。

详见:https://leetcode.com/problems/rectangle-area/description/

Java实现:

class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int sum = (C - A) * (D - B) + (H - F) * (G - E);
        if (E >= C || F >= D || B >= H || A >= G){
            return sum;
        }
        return sum - ((Math.min(G, C) - Math.max(A, E)) * (Math.min(D, H) - Math.max(B, F)));
    }
}

C++实现:

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int sum = (C - A) * (D - B) + (H - F) * (G - E);
        if (E >= C || F >= D || B >= H || A >= G) 
        {
            return sum;
        }
        return sum - ((min(G, C) - max(A, E)) * (min(D, H) - max(B, F)));
    }
};

  参考:https://www.cnblogs.com/grandyang/p/4563153.html

posted on 2018-04-09 10:12  lina2014  阅读(140)  评论(0编辑  收藏  举报

导航