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

来源:互联网 发布:python中延时函数 编辑:程序博客网 时间:2024/05/08 07:37
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 pointsstatic 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);    }}


0 0
原创粉丝点击