41. First Missing Positive
Hard
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:
Your algorithm should run in O(n) time and uses constant extra space.
感觉这题像是为了答案量身打造的一样.这种贪心算法是怎么想出来的
把每个正整数放到对应的索引上即可...
核心思想就是把正整数尽量往索引上放,没有被放的数字一定是特别大的或者是负数,那么这个索引再加上1就是我们要的答案
class Solution { public: int firstMissingPositive(vector<int>& nums) { for(int i=0;i<nums.size();++i) { while(nums[i]>0&&nums[i]<nums.size()&&nums[nums[i]-1]!=nums[i]) swap(nums[i],nums[nums[i]-1]); } for(int i=0;i<nums.size();++i) if(nums[i]!=i+1) return i+1; return nums.size()+1; } };