728x90
Problem
Solution
hash
balls: x위치에 어떤 color 인지 저장
count_colors: 특정 color 가 몇번 등장했는지 count
만약 x 위치의 공이 이미 색칠되어있다면, 해당 색상 - 1
Code
class Solution:
def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]:
n = len(queries)
balls = dict()
count_colors = defaultdict(int)
answer = []
cnt = 0
for i in range(n):
x, color = queries[i]
if x in balls:
# if already colored x, changed color
# count_color[color] - 1
count_colors[balls[x]] -= 1
#특정 색상 수가 0 이되면 dict에서 제거
if count_colors[balls[x]] == 0:
del count_colors[balls[x]]
#x 위치에 색깔 업데이트
balls[x] = color
count_colors[color] += 1
#서로 다른 색상 개수 추가
answer.append(len(count_colors))
return answer
Complexity
Time Complexity
O(N)
Space Complexity
balls , count_colors , answer -> n개 저장
O(N)
728x90
'코딩 테스트' 카테고리의 다른 글
[LeetCode] 2364. Count Number of Bad Pairs (Python) (0) | 2025.02.09 |
---|---|
[LeetCode] 2349. Design a Number Container System (Python) (0) | 2025.02.08 |
[LeetCode] 1726. Tuple with Same Product (Python) (0) | 2025.02.07 |
[LeetCode] 1800. Maximum Ascending Subarray Sum (Python) (0) | 2025.02.04 |
[LeetCode] 3105. Longest Strictly Increasing or Strictly Decreasing Subarray (Python) (0) | 2025.02.03 |
댓글