First Missing Positive

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.

高效算法:O(n) 时间复杂度,O(1)空间复杂度

实现:

  1. int firstMissingPositive(int A[], int n) {
  2. if(n<=0) return 1;
  3. for(int j=0;j<n;) {
  4. if(A[j]>0 && A[j]<n && A[j]!=j && A[A[j]]!=A[j]) {
  5. swap(A[j],A[A[j]]);
  6. }else {
  7. j++;
  8. }
  9. }
  10. for(int j=1;j<n;j++) {
  11. if(A[j]!=j) return j;
  12. }
  13. if(A[0] == n) return n+1;
  14. else return n;
  15. }
posted @ 2014-09-08 23:14  purejade  阅读(92)  评论(0)    收藏  举报