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.
找到第一个没有出现的正整数。
把出现的正整数数值放到与下标一致的位置,至于非正整数出现的位置和重复正整数放置的位置,我们不管。再判断什么位置最先出现不连续的数值,就是答案了
int firstMissingPositive(int A[], int n) { //C++ for(int i = 0; i< n; i++) { if(i == A[i]-1) continue; int j = i; while(A[j] > 0 && A[j] <= n) { if(A[j] == A[A[j]-1]) break; int tmp = A[A[j]-1]; A[A[j]-1] = A[j]; A[j] = tmp; } } int p; for(p = 0; p< n; p++) if(A[p] != p+1) return p+1; if(p == n) return n+1; else return 1; }
[leetcode]First Missing Positive
原文地址:http://blog.csdn.net/chenlei0630/article/details/41411331