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.
技巧性比较强:
参考: http://blog.unieagle.net/2012/09/20/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Afirst-missing-positive/
class Solution { public: int firstMissingPositive(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int outOfRange = n + 2; for(int i = 0; i< n; i++) if(A[i]<=0) A[i] = outOfRange ; int absi; for(int i = 0; i< n; i++) { absi = abs(A[i]); if(absi <= n) { A[absi-1] = -abs(A[absi-1]) ; } } for(int i = 0; i< n; i++) if(A[i] >0) return i+1; return n+1 ; } };