【数学】C034_矩阵重叠(几何想象)

一、题目描述

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:
Both rectangles rec1 and rec2 are lists of 4 integers.
All coordinates in rectangles will be between -10^9 and 10^9.

二、题解

(1) 几何思维

数学思维:判断 r e c 1 rec1 r e c 2 rec2 的长和宽都不相交即可,最后取反即为不存在不相交 == 重叠

/**
 * @date: 1/17/2020 4:17 PM
 * @Execution info:
 *  ·执行用时  ms 击败了 % 的java用户
 *  ·内存消耗 MB 击败了 % 的java用户
 * @Asymptotic Time Complexity:O()
 */
public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
  int rec1_x1 = rec1[0];
  int rec1_y1 = rec1[1];
  int rec1_x2 = rec1[2];
  int rec1_y2 = rec1[3];

  int rec2_x1 = rec2[0];
  int rec2_y1 = rec2[1];
  int rec2_x2 = rec2[2];
  int rec2_y2 = rec2[3];

  // 不存在不相交的情况,即为矩形重叠。不重叠为,rec2在rec1的上/下/左/右
  return !( rec1_x2 <= rec2_x1 ||   // left
            rec2_x2 <= rec1_x1 ||   // right
            rec1_y2 <= rec2_y1 ||   // top
            rec2_y2 <= rec1_y1);    // bottom
}

复杂度分析

  • 时间复杂度: O ( 1 ) O(1)
  • 空间复杂度: O ( 1 ) O(1)
发布了300 篇原创文章 · 获赞 48 · 访问量 8056

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104025004
今日推荐