LeetCode 1057: Campus Bikes Solution
Master LeetCode problem 1057 (Campus Bikes), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1057. Campus Bikes
Problem Explanation
Explanation:
The problem asks to assign each bike to the closest worker based on the Manhattan distance between them. Each worker can only choose one bike, but one bike can be assigned to multiple workers. We need to find the worker-bike pairs that minimize the total Manhattan distance.
To solve this problem, we can use a priority queue to store the distances between each worker and each bike. We will iterate through each worker and for each worker, we will calculate the Manhattan distance to all bikes and store these distances in the priority queue. Then, we will go through the priority queue and assign bikes to workers based on the minimum distance while ensuring that each bike is assigned to at most one worker.
: :
Solution Code
import java.util.*;
class Solution {
public int[] assignBikes(int[][] workers, int[][] bikes) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> {
int comp = Integer.compare(a[0], b[0]);
if (comp == 0) {
if (a[1] == b[1]) {
return Integer.compare(a[2], b[2]);
}
return Integer.compare(a[1], b[1]);
}
return comp;
});
for (int i = 0; i < workers.length; i++) {
for (int j = 0; j < bikes.length; j++) {
int dist = Math.abs(workers[i][0] - bikes[j][0]) + Math.abs(workers[i][1] - bikes[j][1]);
pq.offer(new int[]{dist, i, j});
}
}
int[] result = new int[workers.length];
Arrays.fill(result, -1);
Set<Integer> bikeAssigned = new HashSet<>();
while (bikeAssigned.size() < workers.length) {
int[] assign = pq.poll();
if (result[assign[1]] == -1 && !bikeAssigned.contains(assign[2])) {
result[assign[1]] = assign[2];
bikeAssigned.add(assign[2]);
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1057 (Campus Bikes)?
This page provides optimized solutions for LeetCode problem 1057 (Campus Bikes) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1057 (Campus Bikes)?
The time complexity for LeetCode 1057 (Campus Bikes) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1057 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1057 in Java, C++, or Python.