|  | 
| 1 | 1 | package g1401_1500.s1401_circle_and_rectangle_overlapping; | 
| 2 | 2 | 
 | 
| 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%) | 
| 4 | 4 | 
 | 
| 5 | 5 | public class Solution { | 
| 6 | 6 |  public boolean checkOverlap( | 
| 7 | 7 |  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; | 
| 33 | 17 |  } | 
| 34 | 18 | 
 | 
| 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)); | 
| 37 | 21 |  } | 
| 38 | 22 | } | 
0 commit comments