Rectangle Area

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.

Rectangle Area

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

题目出处:https://leetcode.com/problems/rectangle-area/

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>();
		ls.add(a);
		ls.add(b);
		ls.add(c);
		ls.add(d);
		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;
		}
		
        return totalBef;
    }
	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));
	}
}



阅读更多
文章标签: Java leetcode
个人分类: LeetCode
上一篇Isomorphic Strings
下一篇Implement Queue using Stacks
想对作者说点什么? 我来说一句

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

关闭
关闭