Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- sorting
- 중간
- binary tree
- binary search
- Binary
- Medium
- dfs
- string
- 쉬움
- math
- 이진트리
- matrix
- leetcode
- list
- easy
- recursive
- Array
- hash table
- 문자열
- 리트코드
- Depth-first Search
- Python
- HashTable
- linked list
- 재귀
- 미디움
- two pointers
- DP
- tree
- backtracking
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 136(Single Number, Python) 본문
1. 문제 링크
Single Number - LeetCode
Can you solve this real interview question? Single Number - Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant
leetcode.com
2. 문제 설명
- 정수로 구성된 nums가 주어졌을 때, 한 element만을 제외하곤, 모든 element가 2번 등장한다고 할 때,
- 한번만 등장한 element를 반환
- 제한 조건
- linear runtime complexity, 상수 extra space만 사용할 것
- 예시1) nums = [2,2,1] 이면 1만 1번 등장했으므로 1을 반환
- 예시2) nums = [4,1,2,1,2] 이면 4만 1번 등장했으므로 4를 반환
3. 기존 풀이
- history라는 dictionary를 만들고
- history에 element 별 count를 담은 dict을 구성한 뒤,
- dict의 value가 1일 때의 key값을 반환
class Solution:
def singleNumber(self, nums: List[int]) -> int:
history = {}
for i in nums:
if i not in history:
history[i] = 1
else:
history[i] +=1
for i in history:
if history[i] == 1:
return i
4. 다른 풀이
- XOR 연산자 ^
- 2진수로 바꾸어 연산하는데 0과 1이면 1이 반환되고, 그 외(0과 0, 1과1)는 0을 반환
- 예를 들어, 2^3의 경우 이진수로 10과 11을 연산하여 같은 위치에 1과 1이 있으면 0, 9과 1이 있으면 1이기 때문에 01로 반환되고 십진법으로 하면 1
- 따라서 같은 수가 두번 연산되면 x^x =0이므로 상쇄효과가 존재
- 그리고 이 연산은 교환 법칙이 성립하기에 연산 순서와 상관없이 2번씩 있는 수는 상쇄되어 사라지고 1번 있는 수만 남음
class Solution:
def singleNumber(self, nums: List[int]) -> int:
x = 0
for num in nums:
x ^= num
return x
5. 배운점
- XOR 연산자
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 144(Binary Tree Preorder Traversal, Python) (0) | 2023.12.02 |
---|---|
LeetCode 145(Binary Tree Postorder Traversal, Python) (0) | 2023.12.01 |
LeetCode 141(Linked List Cycle, Python) (0) | 2023.11.29 |
LeetCode 125(Valid Palindrome, Python) (2) | 2023.11.28 |
LeetCode 5(Longest Palindormic Substring, Python)1 (0) | 2023.11.27 |