原题链接在这里:
思路: 方块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 }