zoukankan      html  css  js  c++  java
  • 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 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,新题目,所以没有打败的百分比。

  • 相关阅读:
    手持设备开发项目实例二(盘点扫描系统)
    通过Netty通信,采集设备现场GPS数据,并存放在redis服务器。
    自动立体车库控制应用系统
    Miscorsoft AnalysisServices 开发
    日志分析常用命令
    MVC中 @ResponseBody、@RequestMapping
    spring与redis集成之aop整合方案
    工业控制系统之葡萄酒保温发酵控制系统
    JS闭包分享
    架构之美—数据库架构
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9063963.html
Copyright © 2011-2022 走看看