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));
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值