前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-836-Rectangle Overlap

leetcode-836-Rectangle Overlap

作者头像
chenjx85
发布2018-05-22 16:21:18
5890
发布2018-05-22 16:21:18
举报

题目描述:

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

要完成的函数:

bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) 

说明:

1、给定两个vector,vector第一个元素和第二个元素表示矩形的左下角横坐标和纵坐标,第三个元素和第四个元素表示矩形的右上角横坐标和纵坐标,要求判断这两个矩形是否有共同区域,也就是是否有交集。

2、笔者总是觉得这道题应该有快速的方法判断,而不应该搞一大堆条件判断。

我们先来想一下一维的情况,如何判断两条线段是否重叠,给定两条线段的起始点(left1,right1)和结束点(left2,right2)。

如果两条线段重叠,那么必然有某个x满足max(left1,left2)<x<min(right1,righ2)。

所以推广到二维情况,在横坐标方向上,应该有max(rec1[0],rec2[0])<min(rec1[2],rec2[2]),在纵坐标方向上,应该有max(rec1[1],rec2[1])<min(rec1[3],rec2[3])

所以代码如下,只有一行:

    bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) 
    {
        return max(rec1[0],rec2[0])<min(rec1[2],rec2[2])&&max(rec1[1],rec2[1])<min(rec1[3],rec2[3]);
    }

上述代码实测3ms,新题目,所以没有打败的百分比。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档