-
Notifications
You must be signed in to change notification settings - Fork 22
/
526.load-balancer.cpp
55 lines (47 loc) · 1.23 KB
/
526.load-balancer.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
class LoadBalancer {
private:
unordered_map<int, int> serverMapping;
vector<int> list;
public:
LoadBalancer() {
// do intialization if necessary
}
/*
* @param server_id: add a new server to the cluster
* @return: nothing
*/
void add(int server_id) {
// write your code here
if (serverMapping.count(server_id) > 0)
{
return;
}
list.push_back(server_id);
serverMapping[server_id] = list.size() - 1;
}
/*
* @param server_id: server_id remove a bad server from the cluster
* @return: nothing
*/
void remove(int server_id) {
// write your code here
if (serverMapping.count(server_id) == 0)
{
return;
}
int index = serverMapping[server_id];
serverMapping.erase(server_id);
// exchange with last
list[index] = list[list.size() - 1];
serverMapping[list[index]] = index;
list.pop_back();
}
/*
* @return: pick a server in the cluster randomly with equal probability
*/
int pick() {
// write your code here
int random = rand() % list.size();
return list[random];
}
};