93人阅读 评论(0)

# 1 题目描述

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.

# 2 解题思路

1.总面积 = 矩形A  + 矩形B - A与B相交的部分。

# 3 源代码

package com.larry.easy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RectangleArea {
public boolean isIntersected(int A, int B, int C, int D, int E, int F, int G, int H){
if(A >= G) return false;
if(F >= D) return false;
if(E >= C) return false;
if(B >= H) return false;
return true;
}

public int getMidTwo(int a, int b, int c, int d){
int retn = 0;
List<Integer> ls = new ArrayList<Integer>();
Collections.sort(ls);
retn = ls.get(2) - ls.get(1);
return retn;
}

public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int totalBef = (C-A)*(D-B) + (G-E)*(H-F);//分别计算两个矩形

boolean isInted = isIntersected(A, B, C, D, E, F, G, H);
if(isInted) {//如果相交，则减去相交的部分
int length = getMidTwo(A, C, E, G);
int width = getMidTwo(B, D, F, H);
totalBef = totalBef - length*width;
}

}
public static void main(String[] args) {
/*int a = -3;
int b = 0;
int c = 3;
int d = 4;
int e = 0;
int f = -1;
int g = 9;
int h = 2;*/
/*int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = -1;
int f = -1;
int g = 1;
int h = 1;*/
int a = -2;
int b = -2;
int c = 2;
int d = 2;
int e = 3;
int f = 3;
int g = 4;
int h = 4;

int A = a;
int B = b;
int C = c;
int D = d;
int E = e;
int F = f;
int G = g;
int H = h;
RectangleArea ra = new RectangleArea();
System.out.println(ra.computeArea(A, B, C, D, E, F, G, H));
}
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：23869次
• 积分：668
• 等级：
• 排名：千里之外
• 原创：108篇
• 转载：5篇
• 译文：0篇
• 评论：0条
文章分类
评论排行