题目:
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
思路:
一共两次循环
第一次:从第一个数开始,如果它与这个该在位子上待着的数不一样,这说明,这个数不该在这,
接着判断如果它大于1 小于length,并且它还与它该在的那个位子上的那个数不一样,
那么两个数就可以交换
第二次:从头遍历,如果有数字与这个位子该有的数字不一样,说明找到了,返回 i + 1即可
最后如果都没有,那说明,给的数组可能是类似【1,2,3,4】这种情况,那么返回 length + 1
代码:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int length = nums.size();
int i = 0;
while(i < length)
{
if (nums[i] != i + 1 && nums[i] >= 1 && nums[i] <= length && nums[nums[i] - 1] != nums[i])
{
swap(nums[i], nums[nums[i] - 1]);
}
else
{
i ++;
}
}
for (int i = 0; i < length; ++i)
{
if (nums[i] != (i + 1))
{
return i + 1;
}
}
return length + 1;
}
};