[LeetCode] 836. Rectangle Overlap

An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.

Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.

Given two axis-aligned 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

Constraints:

  • rec1.length == 4
  • rec2.length == 4
  • -109 <= rec1[i], rec2[i] <= 109
  • rec1 and rec2 represent a valid rectangle with a non-zero area.

矩形重叠。

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rectangle-overlap
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道数学题。我给出的思路是去判断两个长方形的可行域是否有交集,如果有,则说明两者有重叠。如何找可行域呢?因为题目说了给的坐标的格式是[x1, y1, x2, y2],前两个数字表示左下角,后两个数字表示右上角。这里计算可行域,我参考了这个帖子

计算出可行域之后,如果同时满足x1 < x2, y1 < y2则说明有重叠,否则就是没有。

时间O(1)

空间O(1)

Java实现

 1 class Solution {
 2     public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
 3         int x1 = Math.max(rec1[0], rec2[0]);
 4         int y1 = Math.max(rec1[1], rec2[1]);
 5         int x2 = Math.min(rec1[2], rec2[2]);
 6         int y2 = Math.min(rec1[3], rec2[3]);
 7         if (x1 < x2 && y1 < y2) {
 8             return true;
 9         } else {
10             return false;
11         }
12     }
13 }

 

相关题目

223. Rectangle Area

836. Rectangle Overlap

LeetCode 题目总结

posted @ 2020-09-07 03:19  CNoodle  阅读(206)  评论(0编辑  收藏  举报