Given an unsorted integer array, find the smallest missing positive integer.
Input: [1,2,0]
Output: 3
The idea is that we need to sort the array. We judge whether a number is missing or not by its index.
If value != index+1, then the missing number is index+1.
We first put all replaced numbers to their right index by swapping. For example, nums[i] is replaced, because the number in its right place is not equal to nums[i]. The right place should be nums[i]-1. So we need to exchange nums[nums[i]-1] with nums[i].
We can’t judge the replaced number by comparing nums[i] with i+1. Because when both nums[0] and nums[1] are 1, then nums[i] != 2 and swap(nums[1], nums[nums[1]-1]) won’t change the array.
1 |
int firstMissingPositive(vector<int>& nums) { |
近期评论