[LeetCode Python3] 41. First Missing Positive 一步步優化
Solution 1:Time O(nlogn); Space O(1)
# Time O(nlogn); Space O(1)
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
nums.sort()
index, size = 0, len(nums)
while index < size and nums[index] < 1:
index += 1
target = 1
while index < size and nums[index] == target:
while index < size and nums[index] == target:
index += 1
target += 1
return target
Solution 2:Time O(n); Space O(n)
# Time O(n); Space O(n)
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
bucket = set()
target = 1
for num in nums:
if num == target:
target += 1
while target in bucket:
bucket.remove(target)
target += 1
elif num > target:
bucket.add(num)
return target
Solution 3:Time O(n); Space O(1)
解法3來自:https://leetcode.com/problems/first-missing-positive/discuss/872224/JavaPython-Supper-Clean-and-Concise-Time-O(N)-Space-O(1)
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n = len(nums)
INF = n + 1
for i in range(n):
if nums[i] <= 0:
nums[i] = INF # marks zero or negative numbers as infinitive positive numbers
for i in range(n):
x = abs(nums[i]) - 1 # use index start with zero
if x < n:
nums[x] = -abs(nums[x]) # mark `x` as visited by marking `nums[x]` as negative
for i in range(n):
if nums[i] > 0: # if nums[i] is positive -> number (i+1) is not visited.
return i + 1
return n + 1
相關文章
- Leetcode 41 First Missing PositiveLeetCode
- 【Leetcode】163. Missing RangesLeetCode
- [LeetCode] 2028. Find Missing ObservationsLeetCode
- LeetCode 41. 缺失的第一個正數LeetCode
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- 一步步搭建 VuePress 及優化【自動化】Vue優化
- leetcode:41. 缺失的第一個正數(困難,陣列)LeetCode陣列
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- 一步步搭建 VuePress 及優化【外掛系列】Vue優化
- Number.POSITIVE_INFINITY
- 一步步搭建 VuePress 及優化【初始化到釋出】Vue優化
- LeetCode刷題(javascript,python3)LeetCodeJavaScriptPython
- 41. The Security Namespacenamespace
- 14-1 雜湊表基礎 / Leetcode first uniq charLeetCode
- leetcode【210】【Depth-first Search】Course Schedule II【c++版本】LeetCodeC++
- LeetCode——python3最長公共字首——2020.11.24LeetCodePython
- 41.交換機
- LeetCode C++ 387. First Unique Character in a String【String/Hash Table】簡單LeetCodeC++
- 【知識點】深度優先搜尋 Depth First Search
- 深度優先搜尋 (Depth First Search 簡稱:DFS)
- Pandas fillna('Missing')
- Missing Subsequence Sum
- API優先(API-first)是一個壞主意! - stilkovAPI
- Leetcode(Python3) 19. Remove Nth Node From End of ListLeetCodePythonREM
- Comodo Positive SSL證書簡要介紹
- missing ) after argument list
- find: missing argument to `-exec'
- Missing MSI and MSP files
- your Android sdk is missingAndroid
- First Blog
- 7.93 FIRST
- leetcode 解題 2.兩數相加-python3 題解LeetCodePython
- :first-child與:first-of-type 區別
- 從零到千萬使用者,我是如何一步步優化MySQL資料庫的?優化MySql資料庫
- 關於Java Chassis 3的契約優先(API First)開發JavaAPI
- gerrit "missing Change-Id"
- OPatch install "Missing command :fuser"
- B. Missing Subsequence Sum