题目描述(Hard)
Given an unsorted integer array, find the smallest missing positive integer.
题目链接
https://leetcode.com/problems/first-missing-positive/description/
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:
扫描二维码关注公众号,回复:
3741738 查看本文章
Your algorithm should run in O(n) time and uses constant extra space.
算法分析
本质是桶排序,每当A[i] != i + 1时,就将A[i]与A[A[i]-1]交换,直到无法交换为止,即将数字放在其应该在的位置。
提交代码:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
const int n = nums.size();
for (int i = 0; i < n; ++i)
{
while (nums[i] != i + 1)
{
if (nums[i] <= 0 || nums[i] > n || nums[i] == nums[nums[i] - 1])
break;
swap(nums[i], nums[nums[i] - 1]);
}
}
for (int i = 0; i < n; ++i)
{
if (nums[i] != i + 1)
return i + 1;
}
return n + 1;
}
};