Monday, July 6, 2015

LeetCode [223] Rectangle Area

 223. Rectangle Area

Medium

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.

The first rectangle is defined by its bottom-left corner (A, B) and its top-right corner (C, D).

The second rectangle is defined by its bottom-left corner (E, F) and its top-right corner (G, H).

 

Example 1:

Rectangle Area
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45

Example 2:

Input: A = -2, B = -2, C = 2, D = 2, E = -2, F = -2, G = 2, H = 2
Output: 16

 

Constraints:

  • -104 <= A, B, C, D, E, F, G, H <= 104
Accepted
118,261
Submissions
308,367

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int area1 = (C-A)*(D-B);
        int area2 = (G-E)*(H-F);
        
        int overlap = 0;
        if(Math.min(C, G)>Math.max(A, E) && Math.min(D,H)>Math.max(B, F)){
            overlap = (Math.min(C, G)-Math.max(A, E))*(Math.min(D,H)-Math.max(B, F));
        }
        
        return area1 + area2 - overlap;
    }
}

No comments:

Post a Comment