[LintCode] First Missing Positive
public int firstMissingPositive(int[] A) { // write your code here if(A == null || A.length == 0) return 1; int i = 0; int n = A.length; while(i < n) { if(A[i] >= 0 && A[i] < n && A[A[i]] != A[i]) swap(A, i, A[i]); else i++; } int k = 1; while(k < n && A[k] == k) k++; if(k < n) return k; else return k+1; } public void swap(int[] A, int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; }
Leave A Comment