My cpp solution


  • 1
    N

    Actually I read the SFML game engine source code, and got this solution.

    class Solution {
    public:
    
    	int AreaOfRec(int Left, int Bottom, int Right, int Top)
    	{
    		int result = (Right > Left && Top > Bottom) ? ((Right - Left) * (Top - Bottom)) : 0;
    		return result;
    	}
    
    
    	int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    		int Left1 = A;
    		int Bottom1 = B;
    		int Right1 = C;
    		int Top1 = D;
    
    		int Left2 = E;
    		int Bottom2 = F;
    		int Right2 = G;
    		int Top2 = H;
    
    		auto interLeft = max(Left1, Left2);
    
    		auto interRight = min(Right1, Right2);
    
    		auto interTop = min(Top1, Top2);
    		
    		auto interBottom = max(Bottom1, Bottom2);
    
    		return  AreaOfRec(Left1, Bottom1, Right1, Top1) + AreaOfRec(Left2, Bottom2, Right2, Top2) - AreaOfRec(interLeft, interBottom, interRight, interTop);
    	}
    
    };

  • 0
    A

    Not quite understand why sometimes use min sometimes use max


  • 0
    E

    class Solution
    {
    public:

    int maxHorizon(int v1, int v2, int v3, int v4)
    {
    	int maxValue = 0;
    	maxValue = max(maxValue,v1);
    	maxValue = max(maxValue,v2);
    	maxValue = max(maxValue,v3);
    	maxValue = max(maxValue,v4);
    	return maxValue;
    }
    
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int width1 = abs(A - C);
    	int width2 = abs(E - G);
    	int totalWidth = maxHorizon(abs(A - G), abs(E - C), width1, width2);
    	int widthIntersected = width1 + width2 - totalWidth;
    	
    	int height1 = abs(B - D);
    	int height2 = abs(F - H);
    	int totalHeight = maxHorizon(abs(B - H), abs(D - F), height1, height2);
    	int heightIntersected = height1 + height2 - totalHeight;
    	
    	int area1 = width1 * height1;
    	int area2 = width2 * height2;
    	
    	
    	if(widthIntersected <= 0 || heightIntersected <= 0)
    	{
    		///does not intersect
    		return area1 + area2;
    	}
    	else
    	{
    		///intersect
    		return area1 + area2 - widthIntersected * heightIntersected;
    	}
    }
    

    };


Log in to reply
 

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