forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesign-a-file-sharing-system.cpp
112 lines (100 loc) · 3.06 KB
/
design-a-file-sharing-system.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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Time: ctor: O(1)
// join: O(logu + c), u is the number of total joined users
// leave: O(logu + c), c is the number of chunks
// request: O(u)
// Space: O(u * c)
// "u ~= n" solution, n is the average number of users who own the chunk
class FileSharing {
public:
FileSharing(int m) {
}
int join(vector<int> ownedChunks) {
int userID = users_.size() + 1;
if (!min_heap_.empty()) {
userID = min_heap_.top();
min_heap_.pop();
} else {
users_.emplace_back();
}
for (const auto& chunk : ownedChunks) {
users_[userID - 1].emplace(chunk);
}
lookup_.emplace(userID);
return userID;
}
void leave(int userID) {
if (!lookup_.count(userID)) {
return;
}
lookup_.erase(userID);
users_[userID - 1].clear();
min_heap_.emplace(userID);
}
vector<int> request(int userID, int chunkID) {
vector<int> result;
for (int i = 0; i < users_.size(); ++i) {
if (users_[i].count(chunkID)) {
result.emplace_back(i + 1);
}
}
if (!result.empty()) {
users_[userID - 1].emplace(chunkID);
}
return result;
}
private:
vector<unordered_set<int>> users_;
unordered_set<int> lookup_;
priority_queue<int, vector<int>, greater<int>> min_heap_;
};
// Time: ctor: O(1)
// join: O(logu + c), u is the number of total joined users
// leave: O(logu + c), c is the number of chunks
// request: O(nlogn) , n is the average number of users who own the chunk
// Space: O(u * c + m)
// "u >> n" solution
class FileSharing2 {
public:
FileSharing2(int m) {
}
int join(vector<int> ownedChunks) {
int userID = users_.size() + 1;
if (!min_heap_.empty()) {
userID = min_heap_.top();
min_heap_.pop();
} else {
users_.emplace_back();
}
for (const auto& chunk : ownedChunks) {
users_[userID - 1].emplace(chunk);
chunks_[chunk].emplace(userID);
}
lookup_.emplace(userID);
return userID;
}
void leave(int userID) {
if (!lookup_.count(userID)) {
return;
}
lookup_.erase(userID);
for (const auto& chunk : users_[userID - 1]) {
chunks_[chunk].erase(userID);
}
users_[userID - 1].clear();
min_heap_.emplace(userID);
}
vector<int> request(int userID, int chunkID) {
vector<int> result(cbegin(chunks_[chunkID]), cend(chunks_[chunkID]));
sort(begin(result), end(result));
if (!result.empty()) {
users_[userID - 1].emplace(chunkID);
chunks_[chunkID].emplace(userID);
}
return result;
}
private:
vector<unordered_set<int>> users_;
unordered_set<int> lookup_;
unordered_map<int, unordered_set<int>> chunks_;
priority_queue<int, vector<int>, greater<int>> min_heap_;
};