【多次过】Lintcode 626. 矩形重叠

给定两个矩形,判断这两个矩形是否有重叠。

样例

给定 l1 = [0, 8], r1 = [8, 0], l2 = [6, 6], r2 = [10, 0], 返回 true

给定 l1 = [0, 8], r1 = [8, 0], l2 = [9, 6], r2 = [10, 0], 返回 false

解题思路:

    一开始想了很多种情况,但是这样太复杂了。由于这里矩形都是与坐标轴平行的,所以分别投影到x轴与y轴,判断投影后的线段是否重合即可。

    首先,比如一维的情况,两条线段[l1,r1][l2,r2]相重叠,必须满足max(l1,l2)<=min(r1,r2),然后同理推广到x轴与y轴投影中。

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */

class Solution {
public:
    /**
     * @param l1: top-left coordinate of first rectangle
     * @param r1: bottom-right coordinate of first rectangle
     * @param l2: top-left coordinate of second rectangle
     * @param r2: bottom-right coordinate of second rectangle
     * @return: true if they are overlap or false
     */
    bool doOverlap(Point &l1, Point &r1, Point &l2, Point &r2) 
    {
        // write your code here
        return max(l1.x,l2.x)<=min(r1.x,r2.x) && max(r1.y,r2.y)<=min(l1.y,l2.y);
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80792665