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
判断给定的两个矩形是否有重叠,如果有重叠,则返回true.
假如重叠的话,
左边界值:max(rec1[0], rec2[0]),右边界值:min(rec1[2], rec2[2]),
下边缘值:max(rec1[1], rec2[1]),上边缘值:min(rec1[3], rec2[3])
重叠的条件为:左边界 < 右边界 && 下边缘 < 上边缘.
代码如下:
/**************************************************************************
*
* 836. [Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap/)
*
* An axis-aligned rectangle is represented as a list [x1, y1, x2, y2],
* where (x1, y1) is the coordinate of its bottom-left corner,
* and (x2, y2) is the coordinate of its top-right corner.
* Its top and bottom edges are parallel to the X-axis, and its left and
* right edges are parallel to the Y-axis. 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 rec1 and rec2, return true if they overlap,
* otherwise return false.
*
* 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
*
**************************************************************************/
#define MAX(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
#define MIN(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
bool isRectangleOverlap(int* rec1, int rec1Size, int* rec2, int rec2Size){
if (NULL == rec1 || NULL == rec2 || rec1Size != 4 || rec2Size != 4) return false;
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];
int leftBoundary = MAX(rec1_x1, rec2_x1);
int ringhtBoundary = MIN(rec1_x2, rec2_x2);
int bottomBoundary = MAX(rec1_y1, rec2_y1);
int topBoundary = MIN(rec1_y2, rec2_y2);
return leftBoundary < ringhtBoundary && bottomBoundary < topBoundary;
}
简化后代码:
bool isRectangleOverlap(int* rec1, int rec1Size, int* rec2, int rec2Size){
if (NULL == rec1 || NULL == rec2 || rec1Size != 4 || rec2Size != 4) return false;
return MAX(rec1[0], rec2[0]) < MIN(rec1[2], rec2[2]) && \
MAX(rec1[1], rec2[1]) < MIN(rec1[3], rec2[3]);
}