#836 Rectangle Overlap

#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.

Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true

Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rectangle-overlap

解题思路

两种解法,主要注重思想:

第一种解法:

当正面思考该问题逻辑比较复杂的时候,可以尝试思考它的补集。

如这道题的补集为:rect1的最右边小于rect2的最左边,或rect1的最上边小于rect2的最下边,以及其他两种情况。四种情况满足任何一种都可以说明两个矩形无交集。

第二种解法:

是在处理图形的问题的时候,可以尝试将其映射到\(x\)\(y\)轴上,利用投影解决问题。

如图所示,在\(x\)轴上只要\(min(a_2,b_2)>max(a_1,b_1)\),同时满足\(y\)轴上的相关公式,即可证明两矩形必定相交。

代码解释

代码比较简单,不再解释。

Github

posted @ 2020-03-22 16:09  Lyu1997  阅读(124)  评论(0编辑  收藏  举报