-->

Sunday, January 1, 2017

223. Rectangle Area

https://leetcode.com/problems/rectangle-area/

Solution:
An interesting question. Looks like very simple, but not easy to code initially. However, after careful thinking, it is quick straightforward. If the minimum of the two right edge smaller than the maximum of the two left edge, then there's no overlap; similar argument can also be applied on the y-axis.

Further thinking:
1): how about more than two rectangles? A simple solution is calculate the overlap of any pairs of rectangles with time complexity of O(n2). Is there a better one?
2): Similar to Skyline problem, how to solve the "rectangle-line problem"?

Code:
class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int res = 0;
        res += (C-A)*(D-B) + (G-E)*(H-F);
        if(min(C, G)>max(A, E) && min(D, H)>max(B, F))//avoiding overflow problem. 
        res -= (min(C, G)-max(A, E))*(min(D, H)-max(B, F));
        return res;
    }
};

No comments :

Post a Comment