https://leetcode.com/problems/single-number/
Single Number - 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
<문제>
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
<예시>
Input: nums = [4,1,2,1,2] Output: 4
# x xor x = 0 이라는 것을 이용한 아이디어!
class Solution3:
def singleNumber(self, nums: List[int]) -> int:
result = 0
for num in nums:
result ^= num
return result
공유하고 싶은 알고리즘 풀이는 다음과 같다.
X xor X = 0 이라는 것을 이용한 풀이로, 매우 직관적이며 간단한 풀이이다.
XOR을 어떻게 활용할 수 있는지 보여주는 좋은 풀이라고 생각한다.
+) 추가 풀이
class Solution:
def singleNumber(self, nums: List[int]) -> int:
count = defaultdict(int)
for num in nums:
count[num] += 1
ans = [i for i, j in count.items() if j == 1]
return ans[0]
class Solution2:
def singleNumber(self, nums: List[int]) -> int:
nums.sort()
prev = None
for i, num in enumerate(nums[:-1]):
if num != prev and num != nums[i + 1]:
return num
prev = num
return nums[-1]
'다전공_컴퓨터공학 > 알고리즘 문제풀이' 카테고리의 다른 글
[파이썬 알고리즘] 21장 그리디 알고리즘 - 키 대기열 (heapq) (0) | 2021.02.26 |
---|---|
[프로그래머스] 이분탐색 > 입국심사 (이분탐색을 어떻게 적용할 것인가?) (0) | 2021.02.23 |
[파이썬 알고리즘] 17장 - 색 정렬 (leetcode 75) - 3 pointer 문제 (0) | 2021.01.29 |
[파이썬 알고리즘] 17장 가장 큰 수 (leetcode 179) - merge sort 이용 (0) | 2021.01.29 |
[프로그래머스] 그래프 - 순위 (0) | 2021.01.22 |