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.

 1 public class Solution {
 2     public int firstMissingPositive(int[] A) {
 3         if(A.length<=0) return 1;
 4         int n = A.length;
 5         for(int i=0;i<n;i++){
 6             if(A[i]<=0){
 7                 A[i]=n+2;
 8             }
 9         }
10         for(int i=0;i<n;i++){
11             int temp = Math.abs(A[i]);
12             if(temp<=n){
13                 A[temp-1] = -Math.abs(A[temp-1]);
14             }
15         }
16         for(int i=0;i<n;i++){
17             if(A[i]>0){
18                 return i+1;
19             }
20         }
21         return n+1;
22     }
23 }
View Code

 should be (index<=n), ex. {1}

posted @ 2014-02-06 14:13  krunning  阅读(111)  评论(0编辑  收藏  举报