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.
因为不能额外使用空间,所以不能用HashTable,利用原本的数组记录状态。将值为正整数的数字放到对应值-1的下标位置。
注意无限循环:比如[1,1],所以nums[nums[i]-1]==nums[i]的情况要排除。
class Solution { public int firstMissingPositive(int[] nums) { int tmp; int i = 0; while(i < nums.length){ if(nums[i] < nums.length && nums[i] > 0 && nums[i] != i+1 && nums[nums[i]-1]!=nums[i]){ //put nums[i] at position of nums[i]-1 tmp = nums[i]; nums[i] = nums[tmp-1]; nums[tmp-1] = tmp; } else{ i++; } } for(i = 0; i < nums.length; i++){ if(nums[i] != i+1) break; } return i+1; }}