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 (axis-aligned) 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.

    矩形重叠。题意是给两个长方形的左下角和右上角的坐标,请你判断这两个长方形是否有重叠。

    这是一道数学题。我给出的思路是去判断两个长方形的可行域是否有交集,如果有,则说明两者有重叠。如何找可行域呢?因为题目说了给的坐标的格式是[x1, y1, x2, y2],前两个数字表示左下角,后两个数字表示右上角。这里计算可行域,我参考了这个帖子

    计算出可行域之后,如果同时满足x1 < x2, y1 < y2则说明有重叠,否则就是没有。

    时间O(1)

    空间O(1)

    Java实现

     1 class Solution {
     2     public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
     3         int x1 = Math.max(rec1[0], rec2[0]);
     4         int y1 = Math.max(rec1[1], rec2[1]);
     5         int x2 = Math.min(rec1[2], rec2[2]);
     6         int y2 = Math.min(rec1[3], rec2[3]);
     7         if (x1 < x2 && y1 < y2) {
     8             return true;
     9         } else {
    10             return false;
    11         }
    12     }
    13 }

    LeetCode 题目总结

  • 相关阅读:
    宏定义中的#
    HDU1506 Largest Rectangle in a Histogram 动态规划
    HDU1864 最大报销额 DP
    POJ2771 Guardian of Decency 最大独立子集
    POJ1698 Alice's Chance 最大流
    HDU1003 Max Sum 动态规划
    eval格式化事件类型的字符串
    C#虚方法virtual详解
    c# 利用反射获得某个类或者对象的所有属性
    windows服务的通常写法
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13624623.html
Copyright © 2011-2022 走看看