-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathdesign-order-management-system.cpp
More file actions
48 lines (41 loc) · 1.52 KB
/
design-order-management-system.cpp
File metadata and controls
48 lines (41 loc) · 1.52 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
// Time: ctor: O(1)
// addOrder: O(1)
// modifyOrder: O(1)
// cancelOrder: O(1)
// getOrdersAtPrice: O(n)
// Space: O(n)
// hash table
class OrderManagementSystem {
public:
OrderManagementSystem() {
}
void addOrder(int orderId, string orderType, int price) {
orders_[orderId] = {orderType, price, size(type_price_[orderType][price])};
type_price_[orderType][price].emplace_back(orderId);
}
void modifyOrder(int orderId, int newPrice) {
const auto orderType = get<0>(orders_[orderId]);
cancelOrder(orderId);
addOrder(orderId, orderType, newPrice);
}
void cancelOrder(int orderId) {
const auto [orderType, price, i] = move(orders_[orderId]);
auto& arr = type_price_[orderType][price];
get<2>(orders_[arr.back()]) = i;
swap(arr[i], arr.back());
arr.pop_back();
if (empty(type_price_[orderType][price])) {
type_price_[orderType].erase(price);
if (empty(type_price_[orderType])) {
type_price_.erase(orderType);
}
}
orders_.erase(orderId);
}
vector<int> getOrdersAtPrice(string orderType, int price) {
return type_price_.count(orderType) && type_price_[orderType].count(price) ? type_price_[orderType][price] : vector<int>();
}
private:
unordered_map<int, tuple<string, int, int>> orders_;
unordered_map<string, unordered_map<int, vector<int>>> type_price_;
};