Judging rectangle overlap-algorithm-first sort by the lower left corner, and then find the non-overlapping situation

LeetCode-836. Rectangular Overlapping

A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of the lower left corner and (x2, y2) are the coordinates of the upper right corner. The top and bottom sides of the rectangle are parallel to the x-axis, and the left and right sides are parallel to the y-axis.

Two rectangles are said to overlap if the area of ​​intersection is positive. To be clear, two rectangles that touch only at corners or edges do not constitute overlap.

Given two rectangles rec1 and rec2. Return true if they overlap; otherwise, return false.

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
example 3:
input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]
output: false
hint:
rect1.length == 4
rect2.length == 4
-109 <= rec1[i], rec2[i] <= 109
rec1 and rec2 represent a valid rectangle whose area is not zero

Problem-solving ideas:

First sort the two rectangles in ascending order of the x-axis at their lower left corners , and sort them in ascending order of the y-axis if the x-axes are equal .
In this way, it is convenient to judge the non-overlapping situation.
The cases of non-overlapping are as follows, and abstracted into codes are 3 cases

insert image description here

package LeetCode_0836矩形重叠;

import java.util.Arrays;
import java.util.Comparator;

class Solution {
    
    
    public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
    
    
        // 如果两个正方形完全相同,则立即返回true
        if (Arrays.equals(rec1, rec2)) {
    
    
            return true;
        }
        int[][] list = {
    
    rec1, rec2};
        Arrays.sort(list, new Comparator<int[]>() {
    
    
            @Override
            public int compare(int[] o1, int[] o2) {
    
    
                return o1[0] == o2[0] ? o1[1] - o2[1] : o1[0] - o2[0];
            }
        });
        rec1 = list[0];
        rec2 = list[1];
        // rec2在rec1上方 不重叠的情况
        boolean b1 = rec2[1] >= rec1[3];
        if (b1) return false;
        // rec2在rec1左侧,不重叠的情况
        boolean b2 = rec2[0] >= rec1[2];
        if (b2) return false;
        // rec2在rec1下方,不重叠的情况
        boolean b3 = rec2[3] <= rec1[1];
        if (b3) return false;

        return true;
    }
}
/*
先按左下角排序,然后找到不重叠的情况即可

 */

Guess you like

Origin blog.csdn.net/Xidian2850/article/details/125058291