Leetcode.836. Rectangles overlap

topic

A list rectangle [x1, y1, x2, y2] expressed in the form, where (x1, y1) coordinates of the lower left corner, (x2, y2) are the coordinates of the upper right corner.

If the intersecting area is positive, called two rectangles overlap. To be clear, the two rectangular sides or only at the corners of the contact does not constitute overlap.

Given two rectangles, it determines whether they overlap and returns the result.

 

Example 1:

Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
Example 2:

Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false

Thinking

1 and 2 rectangular rectangular projection to the x-axis and y-axis to see whether the corresponding segment are superimposed, if there is overlap. Here I used the method to determine overlapping a very violent, and traverse a line segment which point to see if there is another one on the line. Thus it takes O (min (x2-x1, u2-u1)) + O (min (y2-y1, v2-v1)) of the time spent 1304ms test, barely passed.

class Solution {
public:
    bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
        int x1=rec1[0], y1=rec1[1], x2=rec1[2], y2=rec1[3];
        int u1=rec2[0], v1=rec2[1], u2=rec2[2], v2=rec2[3];

        bool xlap=(x2-x1)<=(u2-u1)?overlap(x1, x2, u1, u2): overlap(u1, u2, x1, x2);
        if(!xlap)
            return false;

        bool ylap = (y2-y1)<=(v2-v1)?overlap(y1, y2, v1, v2): overlap(v1, v2, y1, y2);
        if(!ylap)
            return false;

        return true;
    }
    bool overlap(int x1, int x2, int u1, int u2){//O(min(x2-x1, u2-u1)
        for(int i=x1; i<=x2; i++){
            if(u1<i&&i<u2)
                return true;
        }
        return false;
    }
};

optimization

In fact, it can be determined directly from the position of the line segment. . For example: x-axis max (x1, u1) <time min (x2, u2), a line segment x1-x2 and u1-u2 intersect. The same idea, but the code is very simple.

class Solution {
public:
    bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
        return max(rec1[0], rec2[0])<min(rec1[2], rec2[2]) && max(rec1[1], rec2[1])<min(rec1[3], rec2[3]);
    }
};

 

Published 18 original articles · won praise 0 · Views 782

Guess you like

Origin blog.csdn.net/afiguresomething/article/details/104945942