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
时间复杂度要求O(n),空间复杂度要求O(1)
解题思路:数学问题,相当于手动排序,如果最后数字1在1号位置,数字2在2号位置...那么最终直接扫描一遍数组就可知道缺失哪一个正整数。需要注意的是,n个位置放置的是0-n-1,为了处理的方便,nums的容量加一。
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
nums.push_back(0);
for(int i = 0; i < n; ++ i){
if(nums[i] >= 0 && nums[i] <= n && nums[nums[i]] != nums[i]){
swap(nums[i], nums[nums[i]]);
-- i;
}
}
for(int i = 1; i <= n; ++ i)
if(nums[i] != i)
return i;
return n+1;
}
};