class Solution {
public:
bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {
// 首先先来最简单的检查,如果 xCenter, yCenter 在矩形内,肯定有交叠
if(x1<=xCenter&&xCenter<=x2&&y1<=yCenter&&yCenter<=y2){
return true;
}
// 其他情况下就是要找到矩形上距离圆最近的点
double nearestX = max((double)x1, min((double)xCenter, (double)x2));
double nearestY = max((double)y1, min((double)yCenter, (double)y2));
double dx = nearestX - xCenter;
double dy = nearestY - yCenter;
return dx * dx + dy * dy <= (double)radius * radius;
}
};
最新回复 (4)
Lvvvv09-19 10:27
1楼
计算几何完全不会
class Solution {
public:
bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {
int closestX = max(x1, min(xCenter, x2));
int closestY = max(y1, min(yCenter, y2));
int dx = xCenter - closestX;
int dy = yCenter - closestY;
return dx * dx + dy * dy <= radius * radius;
}
};
CPython09-19 10:36
2楼
刚开始用的两个矩形判断 结果就是有一个样例过不去, 还是看了题解
class Solution:
def checkOverlap(self, radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool:
def f(i, j, k):
if i <= k <= j:
return 0
return i - k if k < i else j - k
x, y = f(x1, x2, xCenter), f(y1, y2, yCenter)
return x * x + y * y <= radius * radius
魔法师09-20 08:55
3楼
我好像想复杂了
代码
public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {
// 彻底远离的情况
if (x1 > xCenter + radius || y1 > yCenter + radius || x2 < xCenter - radius || y2 < yCenter - radius) {
return false;
}
// 矩形包含圆心的情况
if (x1 < xCenter && y1 < yCenter && x2 > xCenter && y2 > yCenter) {
return true;
}
// 矩形不包含圆心,那矩形的四条线与圆形交点的连线一定包含矩形的部分
int rSquared = radius * radius;
return (checkIntersection(xCenter, yCenter, x1, y1, x2, y2, rSquared) ||
checkIntersection(yCenter, xCenter, y1, x1, y2, x2, rSquared));
}
public class Solution {
public bool CheckOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {
if(xCenter >= x1 && xCenter <= x2 && yCenter >= y1 && yCenter <= y2) return true;