leetcode/solution/0800-0899/0836.Rectangle Overlap/README.md

3.8 KiB
Raw Permalink Blame History

comments difficulty edit_url tags
true 简单 https://github.com/doocs/leetcode/edit/main/solution/0800-0899/0836.Rectangle%20Overlap/README.md
几何
数学

836. 矩形重叠

English Version

题目描述

矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。矩形的上下边平行于 x 轴,左右边平行于 y 轴。

如果相交的面积为 ,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。

给出两个矩形 rec1rec2 。如果它们重叠,返回 true;否则,返回 false

 

示例 1

输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3]
输出:true

示例 2

输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1]
输出:false

示例 3

输入:rec1 = [0,0,1,1], rec2 = [2,2,3,3]
输出:false

 

提示:

  • rect1.length == 4
  • rect2.length == 4
  • -109 <= rec1[i], rec2[i] <= 109
  • rec1rec2 表示一个面积不为零的有效矩形

解法

方法一:判断不重叠的情况

我们记矩形 \text{rec1} 的坐标点为 (x_1, y_1, x_2, y_2),矩形 \text{rec2} 的坐标点为 (x_3, y_3, x_4, y_4)

那么当满足以下任一条件时,矩形 \text{rec1}\text{rec2} 不重叠:

  • 满足 y_3 \geq y_2,即 \text{rec2}\text{rec1} 的上方;
  • 满足 y_4 \leq y_1,即 \text{rec2}\text{rec1} 的下方;
  • 满足 x_3 \geq x_2,即 \text{rec2}\text{rec1} 的右方;
  • 满足 x_4 \leq x_1,即 \text{rec2}\text{rec1} 的左方。

当以上条件都不满足时,矩形 \text{rec1}\text{rec2} 重叠。

时间复杂度 O(1),空间复杂度 O(1)

Python3

class Solution:
    def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
        x1, y1, x2, y2 = rec1
        x3, y3, x4, y4 = rec2
        return not (y3 >= y2 or y4 <= y1 or x3 >= x2 or x4 <= x1)

Java

class Solution {
    public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
        int x1 = rec1[0], y1 = rec1[1], x2 = rec1[2], y2 = rec1[3];
        int x3 = rec2[0], y3 = rec2[1], x4 = rec2[2], y4 = rec2[3];
        return !(y3 >= y2 || y4 <= y1 || x3 >= x2 || x4 <= x1);
    }
}

C++

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 x3 = rec2[0], y3 = rec2[1], x4 = rec2[2], y4 = rec2[3];
        return !(y3 >= y2 || y4 <= y1 || x3 >= x2 || x4 <= x1);
    }
};

Go

func isRectangleOverlap(rec1 []int, rec2 []int) bool {
	x1, y1, x2, y2 := rec1[0], rec1[1], rec1[2], rec1[3]
	x3, y3, x4, y4 := rec2[0], rec2[1], rec2[2], rec2[3]
	return !(y3 >= y2 || y4 <= y1 || x3 >= x2 || x4 <= x1)
}

TypeScript

function isRectangleOverlap(rec1: number[], rec2: number[]): boolean {
    const [x1, y1, x2, y2] = rec1;
    const [x3, y3, x4, y4] = rec2;
    return !(y3 >= y2 || y4 <= y1 || x3 >= x2 || x4 <= x1);
}