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.
找到第一个丢失的正整数~思路用到了Counting sort~可以利用数组的index来作为数字本身的索引,把正数按照递增顺序依次放到数组中,即让A[0]=1, A[1]=2, A[2]=3 , 最后如果哪个数组元素不满足A[i]=i+1就说明i+1就是第一个缺失的正数~对于不在范围内的数字,比如说负数,0,或者超过数组长度的正数,可以直接跳过~这题之前做过一次还是不太熟啊~对Counting Sort之前也不是很熟悉~
class Solution:
# @param A, a list of integers
# @return an integer
def firstMissingPositive(self, A):
if A is None or len(A) == 0:
return 1
for i in xrange(len(A)):
while A[i] > 0 and A[i] <= len(A) and A[A[i] - 1] != A[i]:
A[A[i] - 1], A[i] = A[i], A[A[i] - 1]
for i in xrange(len(A)):
if A[i] != i + 1:
return i + 1
return len(A) + 1