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