lintcode_189. 丢失的第一个正整数
给出一个无序的整数数组,找出其中没有出现的最小正整数。
样例
如果给出 [1,2,0]
, return 3
如果给出 [3,4,-1,1]
, return 2
class Solution: """ @param: A: An array of integers @return: An integer """ def firstMissingPositive(self, A): # write your code here if not A: return 1 A = sorted(A) ans = 1 for i in A: if i < ans: continue if i > ans: return ans ans += 1 return ans
九章算法参考:
class Solution: # @param A, a list of integers # @return an integer def firstMissingPositive(self, A): # write your code here n = len(A) i = 0 if n == 0: return 1 while i < n: while A[i] != i + 1 and A[i] <= n and A[i] > 0 and A[i] != A[A[i] - 1]: t = A[i] A[i] = A[A[i] - 1] A[t - 1] = t i = i + 1 for i in xrange(n): if A[i] != i + 1: return i + 1 return n + 1