Question

Formatted question description: https://leetcode.ca/all/380.html

 380	Insert Delete GetRandom O(1)

Design a data structure that supports all following operations in average O(1) time.

insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements.
Each element must have the same probability of being returned.

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

Could you implement the functions of the class with each function works in average O(1) time?

@tag-array



Algorithm

Use a one-dimensional array and a HashMap, where the array is used to store the numbers, and the HashMap is used to establish the mapping between each number and its position in the array.

For insert operation, first check whether this number already exists in HashMap,

• If it exists, return false directly,
• If it does not exist, insert it at the end of the array, and then create a mapping between the number and its position.

The delete operation is tricky. It is necessary to determine whether it is in the HashMap first,

• If not, return false directly. Because the deletion of HashMap is constant time, but the array is not, in order to make the deletion of the array also constant level, in fact, the number to be deleted and the last number of the array are exchanged, and then the value in the corresponding HashMap is modified. You only need to delete the last element of the array, which ensures deletion within a constant time.

Returning a random number is very simple for an array, as long as a position is randomly generated, the number at that position is returned.

Java