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.

First Missing Positive
 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

First Missing Positive

上一篇:Subsets


下一篇:【新产品发布】EVC9001 USB 隔离器