算法描述:
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.
解题思路:利用数值等于下标加一这一特性。将不符合这一特性的值换到合适的位置,然后扫描下标即可得到结果。
int firstMissingPositive(vector<int>& nums) { if(nums.size()==0) return 1; for(int i=0; i < nums.size(); i++){ while(nums[i] >0 && nums[i] <= nums.size() && nums[nums[i]-1]!=nums[i]) swap(nums[nums[i]-1], nums[i]); } for(int i =0; i< nums.size(); i++) if(nums[i]!=i+1) return i+1; return nums.size()+1; }