Design a data structure that has O(1) add, search, remove, | Hello World
The key here is to use an Array and a HashMap. The array stores the element while the hashMap stores the element as the key and the index in the Array as the value.
Add: Simply add to the end of the array, also add corresponding entries in the hashmap.
Search: Simple search on the Hashmap.
Remove: Remove from the hashMap, swap the index with the last index of the array, then remove the element from the array, update the swapped element in the hashmap.
getRandom: Generate a random index and access the array.
Read full article from Design a data structure that has O(1) add, search, remove, | Hello World
No comments:
Post a Comment