LeetCode-223. Rectangle Area (JAVA)求矩形覆盖面积

223. Rectangle Area

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.

LeetCode-223. Rectangle Area (JAVA)求矩形覆盖面积_第1张图片

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

题意为给定两个矩形的对角坐标,求解两矩形所形成的面积大小。

public int helper(int A, int B, int C, int D, 
		int E, int F, int G, int H) {

	// 看图,上侧取小
	int up = Math.min(D, H);
	// 看图,下侧取大
	int down = Math.max(B, F);

	// 看图,右侧取小
	int right = Math.min(C, G);
	// 看图,左侧取大
	int left = Math.max(A, E);
	// 此种情况说明没有交集
	if (up < down || right < left) {
    	return 0;
	} else {
		// 计算面积
		return (up - down) * (right - left);
	}
}

// A U B = A + B - A * B
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) 
			- helper(A, B, C, D, E, F, G, H);
}


你可能感兴趣的:(leetcode)