-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathdesign-ride-sharing-system.cpp
More file actions
79 lines (66 loc) · 1.84 KB
/
design-ride-sharing-system.cpp
File metadata and controls
79 lines (66 loc) · 1.84 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Time: ctor: O(1)
// addRider: O(1)
// addDriver: O(1)
// matchDriverWithRider: O(1)
// cancelRider: O(1)
// Space: O(n)
// ordered dict
class RideSharingSystem {
public:
RideSharingSystem() {
}
void addRider(int riderId) {
riders_[riderId] = true;
}
void addDriver(int driverId) {
drivers_[driverId] = true;
}
vector<int> matchDriverWithRider() {
if (empty(riders_) || empty(drivers_)) {
return {-1, -1};
}
const auto r = riders_.front().first;
const auto d = drivers_.front().first;
riders_.pop(r);
drivers_.pop(d);
return {d, r};
}
void cancelRider(int riderId) {
if (riders_.count(riderId)) {
riders_.pop(riderId);
}
}
private:
template<typename K, typename V>
class OrderedDict {
public:
int count(const K& key) const {
return lookup_.count(key);
}
V& operator[](const K& key) {
if (!lookup_.count(key)) {
list_.emplace_back();
list_.rbegin()->first = key;
lookup_[key] = prev(end(list_));
}
return lookup_[key]->second;
}
pair<K, V> front() const {
return *cbegin(list_);
}
void pop(const K& key) {
if (!lookup_.count(key)) {
return;
}
list_.erase(lookup_[key]);
lookup_.erase(key);
}
bool empty() const {
return list_.empty();
}
private:
list<pair<K, V>> list_;
unordered_map<K, typename list<pair<K, V>>::iterator> lookup_;
};
OrderedDict<int, bool> riders_, drivers_;
};