[Leetcode 1057] Campus Bikes

原题说明

On a campus represented as a 2D grid, there are N workers and M bikes, with N <= M. Each worker and bike is a 2D coordinate on this grid.

Our goal is to assign a bike to each worker. Among the available bikes and workers, we choose the (worker, bike) pair with the shortest Manhattan distance between each other, and assign the bike to that worker. (If there are multiple (worker, bike) pairs with the same shortest Manhattan distance, we choose the pair with the smallest worker index; if there are multiple ways to do that, we choose the pair with the smallest bike index). We repeat this process until there are no available workers.

The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.

Return a vector ans of length N, where ans[i] is the index (0-indexed) of the bike that the i-th worker is assigned to.

Example 1:

Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
Output: [1,0]
Explanation:
Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is [1, 0].

Example 2:

Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
Output: [0,2,1]
Explanation:
Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is [0,2,1].

Note:

  1. 0 <= workers[i][j], bikes[i][j] < 1000
  2. All worker and bike locations are distinct.
  3. 1 <= workers.length <= bikes.length <= 1000

解题思路

这道题首先可以肯定是要遍历每一对可能的workerbike,计算其距离
如果用priority queue,在pop出来的时候时间复杂度是MNlog(MN)的,这里由于距离最大是2000
所以可以考虑用一个数组buckets来存储每一个距离对应的worker bike组合
即:buckets[i]对应所有距离为iWorkerBikePair
遍历一遍workersbikes,更新buckets
然后:

  1. 用一个数组bike_used记录对应的bike是否被访问过。
  2. 将需要返回的数组记为results,初始化为-1,这样results本身可以用来记录对应的worker是否访问过(-1则未被访问过)
  3. 按顺序遍历buckets数组,并更新resultsbike_used数组即可。

示例代码 (cpp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
struct WorkerBikePair {
int worker;
int bike;
};
public:
vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
// vector<WorkerBikePair> in buckets[i] means all worker bike pairs with distance i.
vector<vector<WorkerBikePair>> buckets(2001, vector<WorkerBikePair>());
for (int i = 0; i < workers.size(); ++i) {
for (int j = 0; j < bikes.size(); ++j) {
int distance = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]);
buckets[distance].push_back(WorkerBikePair{i, j});
}
}
vector<int> results(workers.size(), -1);
vector<bool> bike_used(bikes.size(), false);
for (const auto& bucket : buckets) {
for (const auto& worker_bike_pair : bucket) {
if (!bike_used[worker_bike_pair.bike] && results[worker_bike_pair.worker] == -1) {
bike_used[worker_bike_pair.bike] = true;
results[worker_bike_pair.worker] = worker_bike_pair.bike;
}
}
}
return results;
}
};

示例代码 (java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public int[] assignBikes(int[][] workers, int[][] bikes) {
int n = workers.length;

// order by Distance ASC, WorkerIndex ASC, BikeIndex ASC
PriorityQueue<int[]> q = new PriorityQueue<int[]>((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;
});

// loop through every possible pairs of bikes and people,
// calculate their distance, and then throw it to the pq.
for (int i = 0; i < workers.length; i++) {

int[] worker = workers[i];
for (int j = 0; j < bikes.length; j++) {
int[] bike = bikes[j];
int dist = Math.abs(bike[0] - worker[0]) + Math.abs(bike[1] - worker[1]);
q.add(new int[]{dist, i, j});
}
}

// init the result array with state of 'unvisited'.
int[] res = new int[n];
Arrays.fill(res, -1);

// assign the bikes.
Set<Integer> bikeAssigned = new HashSet<>();
while (bikeAssigned.size() < n) {
int[] workerAndBikePair = q.poll();
if (res[workerAndBikePair[1]] == -1
&& !bikeAssigned.contains(workerAndBikePair[2])) {

res[workerAndBikePair[1]] = workerAndBikePair[2];
bikeAssigned.add(workerAndBikePair[2]);
}
}

return res;
}
}

示例代码 (python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> List[int]:
distances = [] # distances[worker] is tuple of (distance, worker, bike) for each bike
for i, (x, y) in enumerate(workers):
distances.append([])
for j, (x_b, y_b) in enumerate(bikes):
distance = abs(x - x_b) + abs(y - y_b)
distances[-1].append((distance, i, j))
distances[-1].sort(reverse = True) # reverse so we can pop the smallest distance

result = [None] * len(workers)
used_bikes = set()
queue = [distances[i].pop() for i in range(len(workers))] # smallest distance for each worker
heapq.heapify(queue)

while len(used_bikes) < len(workers):
_, worker, bike = heapq.heappop(queue)
if bike not in used_bikes:
result[worker] = bike
used_bikes.add(bike)
else:
heapq.heappush(queue, distances[worker].pop()) # bike used, add next closest bike

return result

复杂度分析

时间复杂度: O(MN) 如果用priority_queue则为O(MNlog(MN))
空间复杂度: O(MN)

归纳总结

我们在Youtube上更新了视频讲解,欢迎关注!

------ 关注公众号:猩猩的乐园 ------