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.
思路:通过index完成标记,遇到1~n之间的数,就交换此数字和此数字为index上的数字,这样走过一遍后,所有1-n的数就都在应该在的位置了, 再遍历一遍找到缺失的就行了。
public int firstMissingPositive(int[] nums) {
int len = nums.length;
for (int i = 0; i < len; i++) {
if (nums[i] <= len && nums[i] >= 1 && nums[i] != nums[nums[i]-1]) {
// System.out.println(i);
swap(nums, nums[i] - 1, i);
i--;
}
}
for (int i = 0; i < len; i++) {
if (nums[i] != i+1) return i+1;
}
return len + 1;
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}