原题链接在这里:https://leetcode.com/problems/rectangle-area/
题目:
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.
Example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45
Note:
Assume that the total area is never beyond the maximum possible value of int.
题解:
方块1面积 + 方块2面积 - 重叠面积
Note: 算重叠的面积时会有overflow, Math.min(C,G) 之前必须加 cast, e.g Math.min(C,G) = -150000001, Math.max(A,E) = 150000000.
原来写(long)(Math.min(C,G) - Math.max(A,E))会报错是因为Math.min(C,G)和Math.max(A,E)都是 Integer, 所以cast之前的结果会default成Integer, 还是会有overflow.
Time Complexity: O(1).
Space: O(1).
AC Java:
1 public class Solution { 2 public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 3 int area1 = (C-A)*(D-B); 4 int area2 = (G-E)*(H-F); 5 6 long width = Math.max((long)Math.min(C,G) - (long)Math.max(A,E), 0); 7 long hight = Math.max((long)Math.min(D,H) - (long)Math.max(B,F), 0); 8 int overflow = (int)(width*hight); 9 10 return area1+area2-overflow; 11 } 12 }
Could avoid overflow as well.
Time Complexity: O(1).
Space: O(1).
AC Java:
1 class Solution { 2 public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 3 return area(A, B, C, D) + area(E, F, G, H) - area(Math.max(A, E), Math.max(B, F), Math.min(C, G), Math.min(D, H)); 4 } 5 6 private int area(int a, int b, int c, int d){ 7 if(a >= c || b >= d){ 8 return 0; 9 } 10 11 return (c - a) * (d - b); 12 } 13 }