[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:
0 <= workers[i][j], bikes[i][j] < 1000
- All worker and bike locations are distinct.
1 <= workers.length <= bikes.length <= 1000
校园自行车分配。题目给了一个2D网格,同时以二维数组给出了一些工人workers和一些自行车bikes在网格里的坐标,其中bikes的数量 >= workers,也就是说肯定会保证每个工人会被分配到一辆自行车。题目同时定义了自行车和工人之间的距离叫做曼哈顿距离,对于网格里的任意两个点,距离公式是
p1
andp2
isManhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|
如果现在工人需要去找一台离TA最近的自行车,请输出每个工人能找到的最近的自行车的index。
思路是桶排序 + 计数排序。因为知道了每个工人的坐标和每个自行车的坐标,所以每个工人和每个自行车两两之间的曼哈顿距离很好算。此时你需要创建一个数组,记录每个工人到每个自行车的距离。bucket sort的用意是在于,如果发现有距离相同的结果,就加到对应距离下的array list。这里bucket sort的桶子表示的是距离,但是桶子里装的是相同距离情况下每一对worker和bike的配对情况。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int[] assignBikes(int[][] workers, int[][] bikes) { 3 int w = workers.length; 4 int b = bikes.length; 5 int[] wo = new int[w]; 6 int[] bi = new int[b]; 7 List<int[]>[] dists = new List[2001]; 8 Arrays.fill(wo, -1); 9 Arrays.fill(bi, -1); 10 for (int i = 0; i < w; i++) { 11 for (int j = 0; j < b; j++) { 12 int[] worker = workers[i]; 13 int[] bike = bikes[j]; 14 // 计算每一个worker和每一个bike之间的曼哈顿距离 15 int dist = Math.abs(worker[0] - bike[0]) + Math.abs(worker[1] - bike[1]); 16 // bucket sort 17 if (dists[dist] == null) { 18 dists[dist] = new ArrayList<int[]>(); 19 } 20 dists[dist].add(new int[] { i, j }); 21 } 22 } 23 24 // 有多少worker已经被分配到了bike 25 int assigned = 0; 26 for (int i = 0; i <= 2000 && assigned < w; i++) { 27 if (dists[i] == null) { 28 continue; 29 } 30 for (int[] pair : dists[i]) { 31 if (wo[pair[0]] == -1 && bi[pair[1]] == -1) { 32 wo[pair[0]] = pair[1]; 33 bi[pair[1]] = pair[0]; 34 assigned++; 35 } 36 } 37 } 38 return wo; 39 } 40 }