题目链接https://leetcode-cn.com/problems/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
Example 2:
Input: nums = [3,4,-1,1]
Output: 2
Example 3:
Input: nums = [7,8,9,11,12]
Output: 1
思路:
线性时间和常数空间确实是不小的要求,思维难度很大。一开始想到遍历一遍数组,对于某个数nums[i]都移动到nums[nums[i]-1]的位置(即下标的位置),然后再遍历一遍数组寻找不连续的地方即可。后来发现需要循环实现,每一次确定一个正确的位置。
最后判断的时候要注意边界条件(刚好是第一个或者len-1的时候缺失)
题解:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int len=nums.size(), index=0;
for(int i=0;i<len;i++){
while(nums[i]>0 && nums[i]<=len && nums[i]!=nums[nums[i]-1]) swap(nums[nums[i]-1],nums[i]);
}
for(int i=0;i<len;i++){
cout<<nums[i]<<" ";
}/* checking the array */
for(int i=0;i<len;i++){
if(i==0 && nums[i]!=1) return 1;
if(i!=len-1 && nums[i+1]!=nums[i]+1) return i+2;
}
return len+1;
}
};