41. First Missing Positive
Given an unsorted integer array nums, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses constant extra space.
Example 1:
Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.
Example 2:
Input: nums = [3,4,-1,1]
Output: 2
Explanation: 1 is in the array but 2 is missing.
思路
我觉得这道题需要注意到的点是 寻找最小缺失正数, 不含0.
这样一来,最理想的状态是 arr[i]=i+1
。
首先把数组 尽可能地 恢复成 上述的理想状态。然后,遍历一遍数组,查缺了哪一位。
public void swap(int[] nums, int i, int j){
int t=nums[i];
nums[i]=nums[j];
nums[j]=t;
}
public int firstMissingPositive(int[] nums) {
int n = nums.length; // nums[i]=i+1
for(int i=0;i<n;i++){
// 注意这里使用的是while, 因为存在下面这种情况
// arr: 4 5 6
// idx: 1 3 4
// swap(1,3) 之后
// arr: 5 4 6
// idx: 1 3 4 // 还需要 swap(1,4) 之后
// 退出循环时,达到理想状态 nums[nums[i]-1]==nums[i]
while(nums[i]>0&&nums[i]<n&&nums[nums[i]-1]!=nums[i]){
swap(nums,i,nums[i]-1);
}
}// end for
for(int i=0;i<n;i++){
if(nums[i]!=i+1){
return i+1;
}
}
return n+1;
}