Load Balancer
此题主要是需要想到对应的数据结构以及数据结构之间的联系以及交互,因为需要随机读取,所以我们必须使用可哈希的数据结构即数组,但是因为我们又需要在O(1)时间进行添加删除,这就需要哈希表了,所以这里的方法就是用一个哈希表和一个数组来互相协助完成工作,对于删除函数,我们需要利用服务器ID找到这个ID在数组中的位置,然后将这个位置与最后一个位置互换从而达到O(1)的操作时间,因为此操作,我们必须同时更新哈希表里面的下标信息,这是此题最需要注意的地方
import random
class LoadBalancer:
def __init__(self):
# Initialize your data structure here.
self.store = {}
self.list = []
self.count = 0
# @param {int} server_id add a new server to the cluster
# @return nothing
def add(self, server_id):
# Write your code here
self.store[server_id] = self.count
self.list.append(server_id)
self.count += 1
# @param {int} server_id remove a bad server from the cluster
# @return nothing
def remove(self, server_id):
# Write your code here
index = self.store[server_id]
self.store[self.list[-1]] = index
self.list[index], self.list[-1] = self.list[-1], self.list[index]
self.list.pop()
self.store.pop(server_id)
self.count -= 1
# @return {int} pick a server in the cluster randomly with equal probability
def pick(self):
# Write your code here
return random.choice(self.list)