Implement a load balancer for web servers. It provide the following functionality:
Add a new server to the cluster =>add(server_id).
Remove a bad server from the cluster =>remove(server_id).
Pick a server in the cluster randomly with equal probability =>pick().
Example
At beginning, the cluster is empty =>{}.
add(1)
add(2)
add(3)
pick()
>> 1 // the return value is random, it can be either 1, 2, or 3.
pick()
>> 2
pick()
>> 1
pick()
>> 3
remove(1)
pick()
>> 2
pick()
>> 3
pick()
>> 3
publicclassLoadBalancer {HashMap<Integer,Integer> sevToLoc;List<Integer> servers;publicLoadBalancer() { sevToLoc =newHashMap<>(); servers =newArrayList<>(); }/* * @param server_id: add a new server to the cluster * @return: nothing */publicvoidadd(int server_id) {sevToLoc.put(server_id,servers.size());servers.add(server_id); }/* * @param server_id: server_id remove a bad server from the cluster * @return: nothing */publicvoidremove(int server_id) {// write your code hereif (sevToLoc.containsKey(server_id)) {int loc =sevToLoc.get(server_id);if (loc !=servers.size() -1) { // 与最后一个交换,删除得比较快int lastServer =servers.get(servers.size() -1);sevToLoc.put(lastServer, loc);servers.set(loc, lastServer); }servers.remove(servers.size() -1); } }/* * @return: pick a server in the cluster randomly with equal probability */publicintpick() {// write your code hereRandom r =newRandom();int loc =r.nextInt(servers.size());returnservers.get(loc); }}