Rectangle Area
2015-07-07 21:01
507 查看
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.
题目出处: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对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统