Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
1. 思路:
就是把【1,n】范围内的数归位,nums数组中大于n的、或者小于等于0的数都不用管
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for(int i = 0; i < n; i++){
while(nums[i] > 0 && nums[i] <= n && nums[nums[i]-1] != nums[i]) //只有在【1,n】范围中的数会归位
swap(nums[nums[i] - 1], nums[i]);
}
for(int i = 0; i < n; i++){
if(nums[i] != i+1)
return i+1;
}
return n+1;
}
};