Best Position for a Service Centre LeetCode solution in Java

1
class Solution {
2
private static final double MIN_STEP = 0.0000001;
3
private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
4

5
public double getMinDistSum(int[][] positions) {
6
double cx = 0, cy = 0;
7
int n = positions.length;
8
for (int[] pos : positions) {
9
cx += pos[0];
10
cy += pos[1];
11
}
12
cx /= n;
13
cy /= n;
14
Node center = new Node(cx, cy, totalDistance(positions, cx, cy));
15

16
double step = 50.0;
17
while (step > MIN_STEP) {
18
Node min = center;
19
for (int[] direction : DIRECTIONS) {
20
double dx = center.x + direction[0] * step, dy = center.y + direction[1] * step;
21
double totalDist = totalDistance(positions, dx, dy);
22
if (totalDist < center.dist) min = new Node(dx, dy, totalDist);
23
}
24
if (center == min) step /= 2;
25
center = min;
26
}
27

28
return center.dist;
29
}
30

31
private double sq(double p) {
32
return p * p;
33
}
34

35
private double dist(int[] pos, double x, double y) {
36
return Math.sqrt(sq(x - pos[0]) + sq(y - pos[1]));
37
}
38

39
private double totalDistance(int[][] positions, double x, double y) {
40
double dist = 0;
41
for (int[] pos : positions) dist += dist(pos, x, y);
42
return dist;
43
}
44

45
private static class Node {
46
double x, y, dist;
47

48
Node(double x, double y, double dist) {
49
this.x = x;
50
this.y = y;
51
this.dist = dist;
52
}
53
}
54
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0