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,新题目,所以没有打败的百分比。

  • 相关阅读:
    gdb常用命令
    linux退格键处理
    JavaScript的MVC模式(转载)
    linux编程 -- 网络编程(一)
    数组操作-将下标变成从0开始的连续数字
    很多学ThinkPHP的新手会遇到的问题
    PHP 统计一维数组value相同的元素的个数num,并将其转化为下标为数字,值是value和num的二维数组
    MySQL数据库使某个不是主键的字段唯一
    利用JS实现表单的自动提交
    thinkphp 使每个模板页都包含一个header文件和一个footer文件
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9063963.html
Copyright © 2011-2022 走看看