Hash - Designing the RandomPool structure

Design a structure with the following three functions:
insert(key): Add a certain key to the structure so that it will not be added repeatedly.
delete(key): Remove a key originally in the structure.

getRandom(): Returns any key in the structure randomly with equal probability .
[Requirement] The time complexity of Insert, delete and getRandom methods are all O(1)

 

Solution: Use two hash tables to operate,

The key value stored in map1 is the corresponding value and the corresponding insertion order

On the contrary in map2, the key value is the corresponding insertion order, and the corresponding value

 

insert(key): the above operation method

getRandom() : just use size, use Math.random() * size  to generate a random number, the range is a value of [0, size ), and then get the value corresponding to the corresponding number from map2

delete(key): It should be noted that if the delete operation is performed directly in map1 and map2, there will be many vacancies. At this time, if getRandom(), the location of the generated random number is likely to be empty. This does not guarantee O(1) time complexity

The correct way is: (overwrite the last one to the corresponding deletion position) If the value at position x is deleted, assign the penultimate value in map1 to the key at x, and assign the value at the corresponding position in map2. value is also assigned the corresponding value

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324879304&siteId=291194637