标签:
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.
#include<iostream> #include<vector> #include<algorithm> using namespace std; struct great_zero :public unary_function<int, bool>{ bool operator()(int&x){ return x > 0; } }; int firstMissingPositive(int A[], int n) { vector<int>T(A, A + n); if (T.empty()) return 1; sort(T.begin(), T.end()); auto iter = find_if(T.begin(), T.end(), great_zero()); if (iter==T.end()) return 1; int target = *iter; if (target > 1) return 1; for (; iter != T.end(); ++iter) { if (*iter - target>1) return target + 1; target = *iter; } return T.back() + 1; }
def firstMissingPositive(A): if len(A)==0: return 1 A.sort() posIdx = None target = None for index in range(len(A)): if A[index]>0: posIdx = index target = A[index] break else: return 1; if target > 1: return 1 for index in range(posIdx+1,len(A)): if A[index]-target>1: return target+1 return A[len(A)-1]+1
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/44171523