Sunday, March 3, 2013

[LeetCode] First Missing Positive


Thought:
Scan the array, if some element is smaller than the target element(the element that should be at this position), we move this element to the right position.

Code:
public class Solution {
    public int firstMissingPositive(int[] A) {
        for (int i = 0; i < A.length; i++) {
            while (A[i] > 0 && A[i] < i + 1 && A[i] != A[A[i] - 1]) {
                int tmp = A[A[i] - 1];
                A[A[i] - 1] = A[i];
                A[i] = tmp;
            }
        }
        for (int i = 0; i < A.length; i++) {
            if (A[i] != i + 1) {
               return i + 1; 
            }
        }
        return A.length + 1;
    }
}

No comments:

Post a Comment