Skip to content

Commit 607889c

Browse files
authored
Improved task 1401.
1 parent 99f2c45 commit 607889c

File tree

1 file changed

+12
-28
lines changed
  • src/main/java/g1401_1500/s1401_circle_and_rectangle_overlapping

1 file changed

+12
-28
lines changed
Lines changed: 12 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,22 @@
11
package g1401_1500.s1401_circle_and_rectangle_overlapping;
22

3-
// #Medium #Math #Geometry #2022_03_25_Time_2_ms_(6.67%)_Space_41.2_MB_(25.00%)
3+
// #Medium #Math #Geometry #2022_04_29_Time_0_ms_(100.00%)_Space_40.5_MB_(68.97%)
44

55
public class Solution {
66
public boolean checkOverlap(
77
int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {
8-
if (x1 <= xCenter && x2 >= xCenter && y1 <= yCenter && y2 >= yCenter) {
9-
return true;
10-
}
11-
int circleDistance = radius * radius;
12-
for (int x = x1; x <= x2; x++) {
13-
if (dist(x, y1, xCenter, yCenter) <= circleDistance) {
14-
return true;
15-
}
16-
}
17-
for (int x = x1; x <= x2; x++) {
18-
if (dist(x, y2, xCenter, yCenter) <= circleDistance) {
19-
return true;
20-
}
21-
}
22-
for (int y = y1; y <= y2; y++) {
23-
if (dist(x1, y, xCenter, yCenter) <= circleDistance) {
24-
return true;
25-
}
26-
}
27-
for (int y = y1; y <= y2; y++) {
28-
if (dist(x2, y, xCenter, yCenter) <= circleDistance) {
29-
return true;
30-
}
31-
}
32-
return false;
8+
// Find the closest point to the circle within the rectangle
9+
int closestX = clamp(xCenter, x1, x2);
10+
int closestY = clamp(yCenter, y1, y2);
11+
// Calculate the distance between the circle's center and this closest point
12+
int distanceX = xCenter - closestX;
13+
int distanceY = yCenter - closestY;
14+
// If the distance is less than the circle's radius, an intersection occurs
15+
int distanceSquared = distanceX * distanceX + distanceY * distanceY;
16+
return distanceSquared <= radius * radius;
3317
}
3418

35-
private int dist(int x1, int y1, int x2, int y2) {
36-
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
19+
private int clamp(int val, int min, int max) {
20+
return Math.max(min, Math.min(max, val));
3721
}
3822
}

0 commit comments

Comments
 (0)