[leetcode][math] Rectangle Area

来源:互联网 发布:sql 子字符串 编辑:程序博客网 时间:2024/05/16 11:43

题目:

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.

Rectangle Area

Assume that the total area is never beyond the maximum possible value of int.

class Solution {public:    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {//ABCD或EFGH或两者都无法构成矩形int area1 = (C - A)*(D - B);int area2 = (G - E)*(H - F);if (area1 <= 0 && area2 <= 0) return 0;if (area1 <= 0) return area2;if (area2 <= 0) return area1;//两个矩形没有重合部分if (C <= E || G <= A || D <= F || H <= B) return area1 + area2;//判断两个矩形的相对位置,确定重合矩形的宽和高(本质:将四个x坐标排序,找到中间两个数,求差得到宽;将四个y坐标排序,找到中间两个数,求差得到高)int width = 0, height = 0;if (A < E){if (G < C) width = G - E;//1包含2else width = C - E;}else{if (C < G) width = C - A;//2包含1else width = G - A;}if (B < F){if (H < D) height = H - F;//1包含2else height = D - F;}else{if (D < H) height = D - B;//2包含1else height = H - B;}int areaOverlap = width * height;return area1 + area2 - areaOverlap;}};


0 0