41. First Missing Positive
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.
把nums[index]交换换到nums[nums[index]-1],再遍历
class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ r_num=1 if nums==None or nums==[]: return r_num n=len(nums) for index in range(n): while nums[index]>0 and nums[index]<=n and nums[index]!=nums[nums[index]-1]: temp=nums[index] nums[index]= nums[nums[index]-1] nums[temp - 1]=temp for index in range(n): if index+1!=nums[index]: return index+1 return n+1