First Missing Positive
Problem link
Given an unsorted integer array, find the smallest missing positive integer.
Example:
Input: [1,2,0]
Output: 3
Discussion :
class Solution { public int firstMissingPositive(int[] A) { int n = A.length; if (n == 0) return 1; for (int i = 0; i < n; ) { if (A[i] > 0 && A[i] <= n && A[A[i]-1] != A[i]){ int a = A[i]; A[i] = A[a - 1]; A[a - 1] = a; } else ++i; } for (int i = 0; i < n; ++i){ if (A[i] != i + 1) return i + 1; } return n+1; } }
Comments
Post a Comment