Accepted C Solution, too simple to explain


  • 8
    R
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    	int area=(C-A)*(D-B)+(G-E)*(H-F);
    	// no overlap
    	if (A>=G||E>=C||B>=H||D<=F)
    	{
    		return area;
    	}
    
    	int x1= A>E?A:E;
    	int x2= C<G?C:G;
    
    	int y1= B>F?B:F;
    	int y2= D<H?D:H;
    
    	return area-(x2-x1)*(y2-y1);
    }
    

    just calculate the areas of two rectangles, and minus the overlap area if exists


  • 0
    J

    nice solution...I use the same idea by my algorithm to compute the duplicate part is more complex....~


  • 2
    Z

    Macro is recommended, I suppose.

    #define MIN(X,Y) ((X)<=(Y)?(X):(Y))
    #define MAX(X,Y) ((X)>=(Y)?(X):(Y))
    
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int overlappedW=(C-A)+(G-E)-(MAX(C,G)-MIN(A,E));
        overlappedW=overlappedW>=0?overlappedW:0;
        int overlappedH=(D-B)+(H-F)-(MAX(D,H)-MIN(B,F));
        overlappedH=overlappedH>=0?overlappedH:0;
        return (C-A)*(D-B)+(G-E)*(H-F)-overlappedW*overlappedH;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.