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.
Seen this question in a real interview before?
Yes
No
- Difficulty:Hard
- Total Accepted:143.3K
- Total Submissions:544.7K
- Contributor:LeetCode
-
Subscribe to see which companies asked this question.
Related Topics Similar QuestionsMissing NumberFind the Duplicate NumberFind All Numbers Disappeared in an ArrayCouples Holding Hands
Wont work for {6, 3, 4, 1, 8, 2}. Your solution assumes that highest integer is less than n.
Why does it not work? In the while loop, one of the conditions is A[i] <= n
, so in this case, 8 won't move, because it's larger than the length. So after the for loop, your array becomes [1,2,3,4,8,6], and 8 != 4+1, so 5 should be returned. Hope this helps.
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int i = 0;
int n = nums.size();
while (i < n)
{
if (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i])
swap(nums[i], nums[nums[i]-1]);
else
i++;
}
for (i = 0; i < n; ++i)
if (nums[i] != (i+1))
return i+1;
return n+1;
}
};
反思
负数和超限值在交换过程中可以进行操作,当要对他们进行nums[nums[i] - 1] != nums[i]这种比较的时候就可以跳过了,让他们站着当前位置,
一来知道缺失哪些值,而来可以根据比较,因为已经把各个位置的数还原了(其实就是相当于排序),只要在n内,不等就知道该位置缺失了
那么这个本来的数就是i+1正整数的原因。
这种交换位置,把各个数安排在本应该在的位置方法经常用到,对于负数和nums[i]>nums.size()这两个坑处理的非常好
另外 find的用法我有时候也没搞清