알고리즘/LeetCode
LeetCode 풀기 - 260. Single Number III
앤테바
2021. 11. 9. 05:54
반응형
260. Single Number III
https://leetcode.com/problems/single-number-iii/
Single Number III - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
제목
문제)
솔루션1)
HashMap or HashSet 자료구조를 통해서 중복을 제거하고 single number만 남겨서 문제를 해결한다.
아래 코드에서는 HashMap 사용.
시간 복잡도 : O(N)
공간 복잡도 : O(N)
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
# Hash
d = {}
for n in nums:
if n in d:
del d[n]
else:
d[n] = None
return list(d.keys())
솔루션2)
Counter() 객체를 사용해서 1번 반복된 숫자를 찾는다.
시간 복잡도 : O(N)
공간 복잡도 : O(N)
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
counter = Counter(nums)
return [n for n, freq in counter.items() if freq == 1]
반응형