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

  • 相关阅读:
    SQL语句 分页实现
    PHPexcel入门教程
    json_decode返回null,使用echo json_last_error(); 返回4
    配置mysql可局域网内访问
    thinkphp5.0安装composer安装topthink/think-captcha
    linux下mysql忘记密码怎么办
    centos7 设置mysql账号密码开放3306端口实现远程登陆
    高级数据结构第七章A . 数列(树状数组逆序对)
    高级数据结构第六章E . 苹果树 (dfs+树状数组)
    高级数据结构第六章C . 奶牛狂欢节(两个树状数组)
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9063963.html
Copyright © 2011-2022 走看看