leetcode-3289. The Two Sneaky Numbers of Digitville

Youngsun Joung·2025년 10월 31일

Leetcode

목록 보기
18/91

1. 문제 소개

3289. The Two Sneaky Numbers of Digitville

2. 나의 풀이법

nums의 모든 숫자를 순회하여 두 번 나타나는 숫자만 골랐다.
시간복잡도는 O(n)O(n)이다.

class Solution:
    def getSneakyNumbers(self, nums: List[int]) -> List[int]:
        detective = dict()
        for n in nums:
            detective[n] = detective.get(n, 0) + 1
        
        ans = []
        for key, value in detective.items():
            if value == 2:
                ans.append(key)
                
        ans.sort()
        return ans

3. 다른 풀이법

이렇게 collections.Counter를 사용하면 한 줄로도 풀 수 있다.

class Solution:
    def getSneakyNumbers(self, nums: List[int]) -> List[int]:
        return sorted([k for k, v in Counter(nums).items() if v == 2])

4. 결론

반복문을 두 번 돌리는 것이 아니라 한 번만 돌려도 된다.

class Solution:
    def getSneakyNumbers(self, nums: List[int]) -> List[int]:
        detective = dict()
        ans = []

        for n in nums:
            detective[n] = detective.get(n, 0) + 1
            if detective[n] == 2:
                ans.append(n)

        ans.sort()
        return ans
profile
Junior AI Engineer

0개의 댓글