728x90
https://leetcode.com/problems/insert-delete-getrandom-o1/description/
Insert Delete GetRandom O(1) - LeetCode
Can you solve this real interview question? Insert Delete GetRandom O(1) - 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 th
leetcode.com
릿코드에는 이런 유형도있구나 생각했습니다.
여러방법이 있지만 깔끔하게 set을 이용해서 문제를 풀었습니다.
한가지 의문이 set.pop() 메서드가 랜덤하게 안 나오고 순차적으로 나와서
음?? 했던...?
import random
class RandomizedSet:
def __init__(self):
self.random_set = set()
self.random_cnt = set()
def insert(self, val: int) -> bool:
if val in self.random_set:
return False
self.random_set.add(val)
return True
def remove(self, val: int) -> bool:
if val not in self.random_set:
return False
self.random_set.remove(val)
return True
def getRandom(self) -> int:
random_num_list = list(self.random_set)
return random.choice(random_num_list)
728x90
'PS > 릿코드' 카테고리의 다른 글
[릿코드 8] String to Integer (atoi) (파이썬/python) (0) | 2023.04.04 |
---|---|
[릿코드 1390] Four Divisors (파이썬/python) (0) | 2023.03.24 |
[릿코드 1466] Reorder Routes to Make All Paths Lead to the City Zero(파이썬/python) (0) | 2023.03.24 |
[릿코드 1297] Maximum Number of Occurrences of a Substring (파이썬/python) (0) | 2023.03.24 |
[릿코드 1319] Number of Operations to Make Network Connected(파이썬/python) (0) | 2023.03.23 |