LeetCode Rectangle Area

Description:

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.

Solution:

分别求面积,然后减去重合部分的即可。

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G,
			int H) {
		return (C - A) * (D - B) + (G - E) * (H - F) - cover(A, C, E, G)
				* cover(B, D, F, H);
	}

	int cover(int a, int b, int c, int d) {
		if (a > c) {
			int temp;

			temp = a;
			a = c;
			c = temp;

			temp = b;
			b = d;
			d = temp;
		}
		if (c >= b)
			return 0;
		if (d <= b)
			return d - c;
		return b - c;
	}
}


阅读更多
文章标签: java leetcode
个人分类: 算法/oj
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭