其他分享
首页 > 其他分享> > [LeetCode] 836. Rectangle Overlap

[LeetCode] 836. Rectangle Overlap

作者:互联网

A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner.

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, return whether they overlap.

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

Notes:

  1. Both rectangles rec1 and rec2 are lists of 4 integers.
  2. All coordinates in rectangles will be between -10^9 and 10^9.

矩形重叠。题意是给两个长方形的左下角和右上角的坐标,请你判断这两个长方形是否有重叠。

这是一道数学题。我给出的思路是去判断两个长方形的可行域是否有交集,如果有,则说明两者有重叠。如何找可行域呢?因为题目说了给的坐标的格式是[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 }

 

LeetCode 题目总结

标签:y2,836,x1,Overlap,x2,y1,rec2,rec1,LeetCode
来源: https://www.cnblogs.com/cnoodle/p/13624623.html