일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 이진탐색
- 그래프
- 우선순위큐
- programmers
- docker
- Kubernetes
- 쿠버네티스
- 알고리즘
- 아파치 스파크
- 티스토리챌린지
- String
- heapq
- 프로그래머스
- Apache Spark
- 오블완
- Python
- 아파치 하둡
- Apache Hadoop
- apache kafka
- 아파치 카프카
- leetcode
- 도커
- 분산처리
- BFS
- 분산
- 코딩테스트
- DP
- 리트코드
- 파이썬
- 문자열
- Today
- Total
래원
[LeetCode] 2349. Design a Number Container System (Python) 본문
[LeetCode] 2349. Design a Number Container System (Python)
Laewon Jeong 2025. 2. 8. 15:37
난이도: Medium
문제 설명
Design a number container system that can do the following:
- Insert or Replace a number at the given index in the system.
- Return the smallest index for the given number in the system.
Implement the NumberContainers
class:
NumberContainers()
Initializes the number container system.void change(int index, int number)
Fills the container atindex
with thenumber
. If there is already a number at thatindex
, replace it.int find(int number)
Returns the smallest index for the givennumber
, or-1
if there is no index that is filled bynumber
in the system.
문제 예제
Example 1:
Input
["NumberContainers", "find", "change", "change", "change", "change", "find", "change", "find"]
[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]
Output
[null, -1, null, null, null, null, 1, null, 2]
Explanation
NumberContainers nc = new NumberContainers();
nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.
nc.change(2, 10); // Your container at index 2 will be filled with number 10.
nc.change(1, 10); // Your container at index 1 will be filled with number 10.
nc.change(3, 10); // Your container at index 3 will be filled with number 10.
nc.change(5, 10); // Your container at index 5 will be filled with number 10.
nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.
nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20.
nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.
제한 사항
1 <= index, number <= 109
- At most
105
calls will be made in total tochange
andfind
.
✏️ Solution(솔루션)
class NumberContainers:
def __init__(self):
self.container = defaultdict(SortedSet)
self.idx = defaultdict(int)
def change(self, index: int, number: int) -> None:
if self.idx[index] != 0:
self.container[self.idx[index]].remove(index)
if not self.container[self.idx[index]]:
del self.container[self.idx[index]]
self.container[number].add(index)
self.idx[index] = number
def find(self, number: int) -> int:
if not self.container[number]:
return -1
return self.container[number][0]
# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)
defaultdict(SortedSet)과 defaultdict(int)를 통해 해결했다.
change에 인자로 들어온 index가 self.idx에 있다면 self.container[self.idx[index]]에 들어가 있는 index를 지워주었다.
이때 self.container[self.idx[index]]의 리스트가 비었다면 del을 통해 아예 삭제 시켜주었다.
그리고 self.container[number].add(index)와 self.idx[index] = number을 통해 새로 업데이트 해주었다.
find는 self.container[number]가 빈 리스트이면 -1을 반환했고, 아니면 제일 작은 index인 self.container[number][0]를 반환했다.
처음에는 다음과 같이 heapq를 통해 진행하였는데 Wrong Answer 판정을 받았다.
import heapq
class NumberContainers:
def __init__(self):
self.container = {}
self.idx = {}
def change(self, index: int, number: int) -> None:
if index in self.idx:
self.container[self.idx[index]].remove(index)
if not self.container[self.idx[index]]:
del self.container[self.idx[index]]
if number not in self.container:
self.container[number] = []
heapq.heappush(self.container[number], index)
self.idx[index] = number
def find(self, number: int) -> int:
if number not in self.container:
return -1
x = heapq.heappop(self.container[number])
heapq.heappush(self.container[number], x)
return x
# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)
이유를 알아보다가 heapq 리스트에서 remove를 사용하면 heapq의 성질이 깨질 수 있다고 한다.
그러다가 알게된 것이 SortedSet이다. 이를 이용하면 제일 앞 요소가 제일 작은 값이기 때문에 좀 더 편하게 사용할 수 있었다.
문제: 2349. Design a Number Container System
깃허브: github
algorithmPractice/LeetCode/2434-design-a-number-container-system at main · laewonJeong/algorithmPractice
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 3174. Clear Digits (Python) (0) | 2025.02.10 |
---|---|
[LeetCode] 2364. Count Number of Bad Pairs (Python) (0) | 2025.02.09 |
[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python) (0) | 2025.02.07 |
[LeetCode] 1726. Tuple with Same Product (Python) (0) | 2025.02.06 |
[LeetCode] 1790. Check if One String Swap Can Make Strings Equal (Python) (0) | 2025.02.05 |