leetcode 1057 - Campus Bikes

https://leetcode.com/problems/campus-bikes/

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
50
51
class Solution {
public:
struct Distance {
int dist;
int worker;
int bike;

Distance(int d, int w, int b) {
dist = d;
worker = w;
bike = b;
}
};

vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
int size = workers.size();
vector<Distance> dist_array;

for (int i = 0; i < size; i++) {
for (int j = 0; j < bikes.size(); j++) {
int dist = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]);
dist_array.push_back(Distance(dist, i, j));
}
}

auto mycomp = [&] (const Distance &d1, const Distance &d2) {
if (d1.dist < d2.dist) return true;
if (d1.dist > d2.dist) return false;
if (d1.worker < d2.worker) return true;
if (d1.worker > d2.worker) return false;
if (d1.bike < d2.bike) return true;
if (d1.bike > d2.bike) return false;

return true;
};

sort(dist_array.begin(), dist_array.end(), mycomp);

vector<int> result(size, -1);
unordered_set<int> used;

for (auto dist : dist_array) {
if (result[dist.worker] == -1 && used.count(dist.bike) == 0) {
result[dist.worker] = dist.bike;
used.insert(dist.bike);
}
}

return result;
}
};