ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 836. Rectangle Overlap

2020-09-07 03:31:20  阅读:329  来源: 互联网

标签:y2 836 x1 Overlap x2 y1 rec2 rec1 LeetCode


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有