| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- Generator
- DWG
- 컴퓨터의 구조
- 715. Range Module
- Python Implementation
- Python
- data science
- 파이썬
- 109. Convert Sorted List to Binary Search Tree
- Decorator
- Substring with Concatenation of All Words
- 운영체제
- 프로그래머스
- 밴픽
- Protocol
- t1
- Regular Expression
- 30. Substring with Concatenation of All Words
- Convert Sorted List to Binary Search Tree
- 43. Multiply Strings
- LeetCode
- 315. Count of Smaller Numbers After Self
- iterator
- 시바견
- concurrency
- kaggle
- shiba
- attribute
- Class
- Python Code
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 |