Skip to content

Commit 220c742

Browse files
authored
Update Campus Bikes.java
1 parent 76b0537 commit 220c742

File tree

1 file changed

+33
-40
lines changed

1 file changed

+33
-40
lines changed

Medium/Campus Bikes.java

Lines changed: 33 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,39 @@
11
class Solution {
2-
public int[] assignBikes(int[][] workers, int[][] bikes) {
3-
PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>(){
4-
public int compare(Node n1, Node n2) {
5-
int c = n1.dist - n2.dist;
6-
if (c != 0) {
7-
return c;
2+
public int[] assignBikes(int[][] workers, int[][] bikes) {
3+
int workerCount = workers.length;
4+
int bikeCount = bikes.length;
5+
PriorityQueue<WorkerBikePair> priorityQueue = new PriorityQueue<>();
6+
for (int i = 0; i < workerCount; i++) {
7+
for (int j = 0; j < bikeCount; j++) {
8+
priorityQueue.add(new WorkerBikePair(manhattanDistance(workers[i], bikes[j]), i, j));
9+
}
810
}
9-
c = n1.workIdx - n2.workIdx;
10-
return c != 0 ? c : n1.cycleIdx - n2.cycleIdx;
11-
}
12-
});
13-
for (int i = 0; i < workers.length; i++) {
14-
for (int j = 0; j < bikes.length; j++) {
15-
pq.add(new Node(getDist(workers[i], bikes[j]), i, j));
16-
}
11+
Set<Integer> bikeDone = new HashSet<>();
12+
int[] result = new int[workerCount];
13+
Arrays.fill(result, Integer.MIN_VALUE);
14+
while (!priorityQueue.isEmpty()) {
15+
WorkerBikePair removed = priorityQueue.remove();
16+
if (result[removed.workerIdx] == Integer.MIN_VALUE && !bikeDone.contains(removed.bikeIdx)) {
17+
result[removed.workerIdx] = removed.bikeIdx;
18+
bikeDone.add(removed.bikeIdx);
19+
}
20+
}
21+
return result;
1722
}
18-
int[] ans = new int[workers.length];
19-
boolean[] bikesTaken = new boolean[bikes.length];
20-
Arrays.fill(ans, Integer.MIN_VALUE);
21-
while (!pq.isEmpty()) {
22-
Node node = pq.remove();
23-
if (ans[node.workIdx] == Integer.MIN_VALUE && !bikesTaken[node.cycleIdx]) {
24-
ans[node.workIdx] = node.cycleIdx;
25-
bikesTaken[node.cycleIdx] = true;
26-
}
23+
24+
private record WorkerBikePair(int manhattanDistance, int workerIdx, int bikeIdx) implements Comparable<WorkerBikePair> {
25+
@Override
26+
public int compareTo(WorkerBikePair o) {
27+
int c = manhattanDistance - o.manhattanDistance;
28+
if (c != 0) {
29+
return c;
30+
}
31+
c = workerIdx - o.workerIdx;
32+
return c != 0 ? c : bikeIdx - o.bikeIdx;
33+
}
2734
}
28-
return ans;
29-
}
30-
31-
private int getDist(int[] p1, int[] p2) {
32-
return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]);
33-
}
34-
}
3535

36-
class Node {
37-
int dist;
38-
int workIdx;
39-
int cycleIdx;
40-
41-
public Node(int dist, int workIdx, int cycleIdx) {
42-
this.dist = dist;
43-
this.workIdx = workIdx;
44-
this.cycleIdx = cycleIdx;
45-
}
36+
private static int manhattanDistance(int[] p1, int[] p2) {
37+
return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]);
38+
}
4639
}

0 commit comments

Comments
 (0)