Tuesday, June 16, 2015

223. Rectangle Area -------------M ~~~~

Q:
Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.
A:
就是简单的找到相交的面积,再减去即可。

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        long maxLeftX = max(A,E);
        long minRightX = min(C,G);
        long width = (minRightX - maxLeftX > 0)? (minRightX -maxLeftX):0;
        long maxBottomY = max(B, F);
        long minUpY = min(D, H);
        long height = (minUpY - maxBottomY >0)? (minUpY - maxBottomY) : 0;
        return int( long(C-A)*(D-B) + long(G-E)*(H-F) - width * height);
    }
};




Mistakes:
1:  虽然结果上说, 最终面积并没有超出。但是不表示中间计算过程的结果不超出int的范围。 因此还是需要 在计算过程中 用long  类型表示。 ( 亦即 计算 length 和 height的时候,可能会溢出 )
   因此所有的中间计算结果都要用long类型




No comments:

Post a Comment