Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0] Output: 3
Example 2:
Input: [3,4,-1,1] Output: 2
Example 3:
Input: [7,8,9,11,12] Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
1 class Solution { 2 public void swap(int[] nums, int a, int b){ 3 int temp = nums[a]; 4 nums[a] = nums[b]; 5 nums[b] = temp; 6 } 7 public int firstMissingPositive(int[] nums) { 8 int n = nums.length; 9 int i = 0; 10 while (i < n) { 11 if (nums[i] > 0 && nums[i] <= n) { 12 if (i != nums[i] - 1 13 && nums[i] != nums[nums[i] - 1]) { 14 swap(nums, i, nums[i] - 1); 15 } else { 16 i++; 17 } 18 } else { 19 i++; 20 } 21 } 22 23 int ans = -1; 24 for (i = 0; i < n; ++i) { 25 if (nums[i] != i + 1) { 26 ans = i + 1; 27 28 break; 29 } 30 } 31 32 return ans == -1 ? n + 1 : ans; 33 } 34 }