【Leetcode】Rectangle Area && Classic Prob: Overlap Rectangle

Overlap Rectangle:
这道题的关键在于:不要去考虑overlap有几种情况,虽然肯定能做出来,但是要考虑的情况太多了,不如就考虑一定不会overlap的情况。无非就是两个rectangle x轴离的太远或者y轴离得太远:
public class overlapRect {
	public static void main(String[] args){
		rect re1 = new rect(1,1,3,-3);
		rect re2 = new rect(2,2,5,-1);
		overlapRect or = new overlapRect();
		System.out.println(or.check(re1, re2));

	}
	
	public boolean check(rect r1, rect r2){
		if(r1.y2 >= r2.y1 || r2.y2 >= r1.y1)
			return false;
		if(r1.x2 <= r2.x1 || r2.x2 <= r1.x1)
			return false;
		return true;
		
	}
	
	//have to ensure the given points are topleft and bottomright points
	static class rect{
		int x1, y1;
		int x2, y2;
		rect(int a, int b, int c, int d){
			this.x1=a;
			this.y1=b;
			this.x2=c;
			this.y2=d;
		}
		
	}
}

当然,你也可以有不同的数据结构,完全在于你以后碰到的题目DS是啥样的。
————————————————————————————————————————————————

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.

————————————————————————————————————————

不废话,直接上代码,题目是让求总面积,无非是overlap不overlap情况,基于overlap rect的判断,简单之极。


public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int total = (C-A)*(D-B) + (G-E)*(H-F);
        //A,B -> bottomleft C,D topright; E,F bottomleft, G,H topright;
        if(C <= E || G <= A)
            return total;
        if(B >= H || F>= D)
            return total;
        int i = Math.max(A,E);
        int j = Math.min(C,G);
        int p = Math.max(B,F);
        int q = Math.min(D,H);
        
        return total - (p-q) * (i-j);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值