#leetcode#Rectangle Area
2015-06-16 02:35
267 查看
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.
注意这题是找总面积, 不是只找overlap的面积, 做题的时候思维定式没看题就直接写了。。
首先判断两矩形有无相交,
若不相交, 则返回两矩形面积之和
若相交, 则再减去相交部分的面积
如何计算相交部分的面积?
首先看行的长度, 两矩形右上顶点横坐标的最小值是相交部分的右边界, 左下顶点横坐标的最大值是左边界, 相减得横边长
同理, 两右上顶点竖坐标的最小值是相交部分的上边界, 左下顶点竖坐标的最大值是下边界,相减得竖边长
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int sum = (D - B) * (C - A) + (H - F) * (G - E);
int overlapArea;
if( E >= C || F >= D || A >= G || B >= H)
overlapArea = 0;
else
overlapArea = (Math.min(C, G) - Math.max(A, E)) * (Math.min(D, H) - Math.max(B, F));
return sum - overlapArea;
}
}
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.
注意这题是找总面积, 不是只找overlap的面积, 做题的时候思维定式没看题就直接写了。。
首先判断两矩形有无相交,
若不相交, 则返回两矩形面积之和
若相交, 则再减去相交部分的面积
如何计算相交部分的面积?
首先看行的长度, 两矩形右上顶点横坐标的最小值是相交部分的右边界, 左下顶点横坐标的最大值是左边界, 相减得横边长
同理, 两右上顶点竖坐标的最小值是相交部分的上边界, 左下顶点竖坐标的最大值是下边界,相减得竖边长
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int sum = (D - B) * (C - A) + (H - F) * (G - E);
int overlapArea;
if( E >= C || F >= D || A >= G || B >= H)
overlapArea = 0;
else
overlapArea = (Math.min(C, G) - Math.max(A, E)) * (Math.min(D, H) - Math.max(B, F));
return sum - overlapArea;
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)