알고리즘 with python
99클럽 코테 스터디 6일차 TIL 힙 :LeetCode 2336. Smallest Number in Infinite Set with Python
정민됴
2024. 5. 25. 17:01
https://leetcode.com/problems/smallest-number-in-infinite-set/description/
문제는 위쪽에서!
힙을 사용하면 간단하게 풀리는 문제였다.
그리고 Infinite Set라면서 num의 제한이 1000까지였다는 어이없는(?)ㅋㅋㅋㅋㅋㅋㅋㅋㅋ
import heapq
class SmallestInfiniteSet:
def __init__(self):
self.hq = [i for i in range(1, 1001)]
heapq.heapify(self.hq)
self.s = set(self.hq)
def popSmallest(self) -> int:
res = heapq.heappop(self.hq)
self.s.remove(res)
return res
def addBack(self, num: int) -> None:
if num not in self.s:
self.s.add(num)
heapq.heappush(self.hq, num)
문제의 조건 중에 중복되는 값은 push하면 안된다고 해서 push할 때 set에 없을 때만 넣어주었다.
파이썬의 class 형식을 알아야 풀 수 있었던 문제같다.
계속 this.hq 이러고 있었다는ㅋㅋㅋㅋㅋㅋ
오늘의 교훈! 조건을 잘 확인하자.