380. Insert Delete GetRandom O(1)

2021. 10. 21. 14:01Leetcode

Description:

Implement the RandomizedSet class:

  • RandomizedSet() Initializes the RandomizedSet object.
  • bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
  • bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
  • int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

You must implement the functions of the class such that each function works in average O(1) time complexity.

 

'''
[1] solution)

base idea::
dictionary search, del, insert operation : O(1)
list remove operation : O(n)
but, list pop operation : O(1)

idea::
__init__(self):
initialize one dictionary for store val, index in list
initialize one list for store values

insert(self,val):
if there is val in dictionary, return False
else append value to list, and insert value, index to dictionary

remove(self,val):
if there is no value in dictionary, return False
else swap val' position and last element in list. then, list.pop() and del dictionary[val], edit last element' index in dictionary

getRandom(self):
return self.list[random.randint(0,len(self.list)-1)]

- T/C: O(1)
- S/C: O(n) # for dictionary and list
'''

import random

class RandomizedSet:

    def __init__(self):
        self.pos={}
        self.nums=[]

    def insert(self, val: int) -> bool:
        if val in self.pos:
            return False
        self.nums.append(val)
        self.pos[val]=len(self.nums)-1
        return True

    def remove(self, val: int) -> bool:
        if val in self.pos:
            idx, last_val =self.pos[val],self.nums[-1]
            self.nums[idx],self.pos[last_val]= last_val, idx
            self.nums.pop()
            del self.pos[val]
            return True
        return False

    def getRandom(self) -> int:
        return self.nums[random.randint(0,len(self.nums)-1)]


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

'Leetcode' 카테고리의 다른 글

1208. Get Equal Substrings Within Budget  (0) 2021.10.21
56. Merge Intervals  (0) 2021.10.21
45. Jump Game II  (0) 2021.10.20
11. Container With Most Water  (0) 2021.10.20
55. Jump Game  (0) 2021.10.20