LeetCode 题解工作台
圆和矩形是否有重叠
给你一个以 (radius, xCenter, yCenter) 表示的圆和一个与坐标轴平行的矩形 (x1, y1, x2, y2) ,其中 (x1, y1) 是矩形左下角的坐标,而 (x2, y2) 是右上角的坐标。 如果圆和矩形有重叠的部分,请你返回 true ,否则返回 false 。 换句话…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数学·结合·几何
答案摘要
对于一个点 $(x, y)$,它到圆心 $(xCenter, yCenter)$ 的最短距离为 $\sqrt{(x - xCenter)^2 + (y - yCenter)^2}$,如果这个距离小于等于半径 ,那么这个点就在圆内(包括边界)。 而对于矩形内(包括边界)的点,它们的横坐标 满足 $x_1 \leq x \leq x_2$,纵坐标 满足 $y_1 \leq y \leq y_2$。…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·几何 题型思路
题目描述
给你一个以 (radius, xCenter, yCenter) 表示的圆和一个与坐标轴平行的矩形 (x1, y1, x2, y2) ,其中 (x1, y1) 是矩形左下角的坐标,而 (x2, y2) 是右上角的坐标。
如果圆和矩形有重叠的部分,请你返回 true ,否则返回 false 。
换句话说,请你检测是否 存在 点 (xi, yi) ,它既在圆上也在矩形上(两者都包括点落在边界上的情况)。
示例 1 :
输入:radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1 输出:true 解释:圆和矩形存在公共点 (1,0) 。
示例 2 :
输入:radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1 输出:false
示例 3 :
输入:radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1 输出:true
提示:
1 <= radius <= 2000-104 <= xCenter, yCenter <= 104-104 <= x1 < x2 <= 104-104 <= y1 < y2 <= 104
解题思路
方法一:数学
对于一个点 ,它到圆心 的最短距离为 ,如果这个距离小于等于半径 ,那么这个点就在圆内(包括边界)。
而对于矩形内(包括边界)的点,它们的横坐标 满足 ,纵坐标 满足 。要判断圆和矩形是否有重叠的部分,相当于在矩形内找到一个点 ,使得 和 都取到最小值,此时若 ,则说明圆和矩形有重叠的部分。
因此,问题转化为求 时 的最小值,以及 时 的最小值。
对于 :
- 如果 ,那么 的最小值为 ;
- 如果 ,那么 的最小值为 ;
- 如果 ,那么 的最小值为 。
同理,我们可以求出 时 的最小值。以上我们可以统一用函数 来处理。
即 , ,如果 ,则说明圆和矩形有重叠的部分。
class Solution:
def checkOverlap(
self,
radius: int,
xCenter: int,
yCenter: int,
x1: int,
y1: int,
x2: int,
y2: int,
) -> bool:
def f(i: int, j: int, k: int) -> int:
if i <= k <= j:
return 0
return i - k if k < i else k - j
a = f(x1, x2, xCenter)
b = f(y1, y2, yCenter)
return a * a + b * b <= radius * radius
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) because it involves a constant number of arithmetic operations, clamping, and a single distance computation. Space complexity is O(1) since no additional data structures are required. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for edge cases where the circle barely touches rectangle corners.
- question_mark
Check if candidates properly handle clamping for nearest rectangle points.
- question_mark
Confirm avoidance of iterating over all rectangle points for efficiency.
常见陷阱
外企场景- error
Forgetting to clamp the center coordinates correctly can give false negatives.
- error
Using Euclidean distance without squaring may cause precision issues or unnecessary computation.
- error
Not handling corner touches separately can fail test cases where the circle grazes the rectangle.
进阶变体
外企场景- arrow_right_alt
Rectangle may be rotated; requires rotated rectangle distance checks.
- arrow_right_alt
Multiple circles overlapping a single rectangle; sum of squared distances for all centers.
- arrow_right_alt
Circle defined by bounding box instead of center/radius; convert to standard circle for overlap check.