41.First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example, Given[1,2,0]return3, and[3,4,-1,1]return2.
Your algorithm should run inO(n) time and uses constant space.
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
Basic idea:
1. for any array whose length is l, the first missing positive must be in range [1,...,l+1],
so we only have to care about those elements in this range and remove the rest.
2. we can use the array index as the hash to restore the frequency of each number within
the range [1,...,l+1]
"""
nums.append(0)
n = len(nums)
for i in range(len(nums)): #delete those useless elements
if nums[i]<0 or nums[i]>=n:
nums[i]=0
for i in range(len(nums)): #use the index as the hash to record the frequency of each number
nums[nums[i]%n]+=n
for i in range(1,len(nums)):
if nums[i]/n==0:
return i
return n
set the index of the corresponding number to negative if the number does not exceed the length of list.
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
for i in xrange(n):
if nums[i] <= 0: nums[i] = len(nums)+1
for i in xrange(n):
if abs(nums[i]) <= n: nums[abs(nums[i])-1] = -abs(nums[abs(nums[i])-1])
for i in xrange(n):
if nums[i] > 0: return i+1
return n+1