2014年5月11日星期日

Loop Solution - First Missing Positive *

The idea is to take the advantage of A.length is known, try to exclude all cases to reach a state that [index] == index + 1 like [0] == 1, then the first missing this rule is the one looked for (index + 1)

public class Solution {
    public int firstMissingPositive(int[] A) {
        if(A == null || A.length == 0){
            return 1;
        }
        int i = 0;
        int end = A.length;
        while(i < end){
            if(A[i] == i + 1){
                i++;
                continue;
            }
            if(A[i] <= 0){
                A[i] = 0;
                i++;
            }else if(A[i] > end){
                if(A[i] <= A[end - 1]){
                    A[end - 1] = A[i];
                    A[i] = 0;
                    i++;
                }else{
                    if(A[end - 1] >= end){
                        A[i] = 0;
                        i++;
                    }else{
                        int temp = A[i];
                        A[i] = A[end - 1];
                        A[end - 1] = temp;
                    }
                }
            }else{
                int cur = A[i];
                if(A[cur - 1] == cur){
                    A[i] = 0;
                    i++;
                }else{
                    A[i] = A[cur - 1];
                    A[cur - 1] = cur;
                }
            }
        }
        int j = 0;
        while(j < A.length){
            if(A[j] != j + 1){
                return j + 1;
            }
            j++;
        }
        return j + 1;
    }
}

没有评论: