作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/rectangle-overlap/description/

题目描述:

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, y1)是矩形左下角点的坐标,(x2, y2)是矩形右上角的坐标。

解题方法

方法一:直接比较

求解方法有点烧脑。我在没有画图的情况下想清楚了,所以很快就写出来了。

把rec2当做基准的一个矩形。把rec1跟rec2进行比较。

先判断不想交的情况:

  1. rec1的x2小于rec2的x1;此时rec1在rec2的左边。
  2. rec1的y2小于rec2的y1;此时rec1在rec2的下边。
  3. rec2的x2小于rec1的x1;此时rec1在rec2的右边
  4. rec2的y2小于rec1的y1;此时rec1在rec2的上边。

取not代表相交的情况。

class Solution:
def isRectangleOverlap(self, rec1, rec2):
"""
:type rec1: List[int]
:type rec2: List[int]
:rtype: bool
"""
rec1_x1, rec1_y1, rec1_x2, rec1_y2 = rec1
rec2_x1, rec2_y1, rec2_x2, rec2_y2 = rec2
return not (rec1_x1 >= rec2_x2 or rec1_x2 <= rec2_x1 or rec1_y1 >= rec2_y2 or rec1_y2 <= rec2_y1)

方法二:求相交部分

这个做法和223. Rectangle Area一样,直接根据相对的x, y的大小比较来找出相交部分。如果以x, y为相交部分都大于0的话,那么相交。

class Solution(object):
def isRectangleOverlap(self, rec1, rec2):
"""
:type rec1: List[int]
:type rec2: List[int]
:rtype: bool
"""
[A, B, C, D], [E, F, G, H] = rec1, rec2
x, y = (min(C, G) - max(A, E)), (min(D, H) - max(B, F))
return x > 0 and y > 0

日期

2018 年 5 月 27 日 ———— 周末的天气很好~

最新文章

  1. [AlwaysOn Availability Groups]AlwaysOn等待类型
  2. 开园第一篇 - 论移动开发环境 IOS与Android的差异
  3. mssql 2008 复制订阅
  4. 怎样关闭google的自动更新
  5. Python深入02 上下文管理器
  6. sql 数据库换行
  7. linux,Centos,bash: service: command not found
  8. iOS开发UI基础—手写控件,frame,center和bounds属性
  9. hiveQL去重
  10. Spark学习之数据读取与保存总结(一)
  11. ODM、JDM、OEM概念
  12. 【Topcoder 1879】Scheduling
  13. go使用context包避免goroutine泄露问题
  14. 三: 爬虫之selenium模块
  15. 【MySQL】EXPLAIN命令详解
  16. ORA-01950: no privileges on tablespace xxx ORA-01950: 对表空间 &#39;xxx&#39;无权限
  17. [LeetCode] 101. Symmetric Tree_ Easy tag: BFS
  18. 20145315《网络对抗》——注入shellcode以及 Return-to-libc攻击实验
  19. 关于component-scan中base-package包含通配符的问题探究
  20. Python绘图教程

热门文章

  1. Oracle-除了会排序,你对ORDER BY的用法可能一无所知!
  2. [转]C++中const的使用
  3. 如果你不想让pthread_join阻塞你的进程,那么请调用pthread_detach
  4. InnoDB的行锁模式及加锁方法
  5. 编译安装haproxy2.0
  6. 【Java基础】方法调用机制——MethodHandle
  7. 【力扣】122. 买卖股票的最佳时机 II
  8. Android CameraX 打开摄像头预览
  9. 35、搜索插入位置 | 算法(leetode,附思维导图 + 全部解法)300题
  10. Docker从入门到精通(三)——概念与执行流程