

3289. The Two Sneaky Numbers of Digitville
nums의 모든 숫자를 순회하여 두 번 나타나는 숫자만 골랐다.
시간복잡도는 이다.
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

이렇게 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])

반복문을 두 번 돌리는 것이 아니라 한 번만 돌려도 된다.
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