演算法分析課每週練習 First Missing Positive
阿新 • • 發佈:2019-02-06
題目
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
分析如果把該array中的n放在第n個位置上,那麼遍歷一遍後,第一個位置上不符合的就是要求的值
注:解法比較取巧,好像也沒其他方法,感覺沒有什麼應用價值,不知為什麼是top interview questionclass Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ L=len(nums) for m in range(L): if nums[m]>L: continue val = nums[m]-1 while nums[m]>0 and val<L and nums[val] != nums[m]: nums[m],nums[val]=nums[val],nums[m] val = nums[m]-1 for m in range(len(nums)): if nums[m] != m +1: return m +1 return L+1