[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)

2025. 2. 8. 00:51·코딩 테스트
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
'코딩 테스트' 카테고리의 다른 글
  • [LeetCode] 2364. Count Number of Bad Pairs (Python)
  • [LeetCode] 2349. Design a Number Container System (Python)
  • [LeetCode] 1726. Tuple with Same Product (Python)
  • [LeetCode] 1800. Maximum Ascending Subarray Sum (Python)
zoodi
zoodi
IT/개발 관련 지식을 기록하는 블로그입니다.
  • zoodi
    오늘의 기록
    zoodi
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 후기
        • 컨퍼런스
        • 일상리뷰
      • 금융경제
        • 뉴스
        • 금융IT용어
        • 경제 및 부동산
      • 코딩 테스트
      • 스터디
        • JAVA
        • Kotlin
        • Spring
        • React, Nextjs
        • 인공지능 AI
        • Cloud & k8s
        • Kafka
        • Database
        • Network
        • Algorithm
        • Hadoop
        • LINUX
        • R Programming
        • 기타 (소공, 보안)
      • 도서
      • 기타
  • 블로그 메뉴

    • 홈
    • 스터디
    • 금융경제
    • 후기
    • 기타
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    db
    코딜리티
    코딩
    Kotlin
    스프링부트
    springboot
    알고리즘
    코딩테스트
    이분탐색
    프로그래머스
    코테
    스프링
    쿠버네티스
    자바
    pythoncodingtest
    자료구조
    리트코드
    CodingTest
    kafka
    C++
    java
    codility
    Spring
    Python
    네트워크
    카카오코테
    LeetCode
    코테공부
    MySQL
    금융용어
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
zoodi
[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python)
상단으로

티스토리툴바