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

  • 相关阅读:
    深入Spring之IOC之加载BeanDefinition
    Hexo+GitHub Actions 完美打造个人博客
    Spring中资源的加载原来是这么一回事啊!
    Web 跨域请求问题的解决方案- CORS 方案
    重新认识 Spring IOC
    Spring Data Jpa 入门学习
    前奏:Spring 源码环境搭建
    最短路径——floyd算法代码(c语言)
    leetcode 第184场周赛第一题(数组中的字符串匹配)
    如何用尾插法建立双链表(C语言,非循环)
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9063963.html
Copyright © 2020-2023  润新知