일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 파이썬
- attribute
- DWG
- Convert Sorted List to Binary Search Tree
- Python Implementation
- Class
- 컴퓨터의 구조
- 43. Multiply Strings
- 밴픽
- 715. Range Module
- 109. Convert Sorted List to Binary Search Tree
- 운영체제
- LeetCode
- Python Code
- Generator
- Protocol
- shiba
- 시바견
- t1
- Regular Expression
- Python
- concurrency
- iterator
- data science
- kaggle
- 30. Substring with Concatenation of All Words
- 315. Count of Smaller Numbers After Self
- Substring with Concatenation of All Words
- Decorator
- 프로그래머스
Archives
- Today
- Total
Scribbling
LeetCode: 41. First Missing Positive 본문
The essence of solving this problem within O(N) time complexity & O(1) memory is using the nums array itself as the hash for its numbers. That is, nums[i] should contain the information about whether i-1 is in nums or not.
Here, we should come up with an algorithm that marks nums array without messing up with the original value of nums[i]. Here, I accomplish such an algorithm using negative sign. An alternative would be using 'mod'.
class Solution:
def firstMissingPositive(self, nums):
n = len(nums)
elem = None
for i in range(n):
if 1 <= nums[i] <= n:
elem = nums[i]
break
if not elem:
return 1
# nums[i] is for i-1
for i in range(n):
if nums[i] <= 0 or nums[i] > n:
nums[i] = elem
for num in nums:
nums[abs(num)-1] = -abs(nums[abs(num)-1])
for i, num in enumerate(nums):
if num > 0:
return i + 1
return n + 1
'Computer Science > Coding Test' 카테고리의 다른 글
35. Search Insert Position (0) | 2021.09.08 |
---|---|
LeetCode: 49. Group Anagrams (0) | 2021.09.08 |
LeetCode: 47. Permutations II (0) | 2021.09.07 |
LeetCode: 46. Permutations (0) | 2021.09.07 |
LeetCode: 40. Combination Sum II (0) | 2021.09.07 |