题目链接: https://leetcode.com/problems/first-missing-positive/description/
Description
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.
解题思路
题意为从无序数组中找到第一个缺失的正整数。大致算法为将数组中的正整数放到对应的位置,由于正整数不包含 0,所以对应的位置可以为 正整数 - 1,例如数字 2 放置在下标为 1 的位置。然后从头遍历一遍数组,看哪个位置对应的值不对,就缺失哪个正整数。
具体步骤为,对数组 nums
从头到尾进行遍历,判断第 i
个元素的值是否为 i + 1
。不过要首先判断其值是否大于 0,若不大于 0 则没有意义,因为不能逆向来找 i + 1
填到该处,所以当 nums[i] <= 0
时跳过。另外,若 nums[i]
大于了数组能放置的最大正整数,即数组大小(nums[size - 1] = size
),也只能跳过。通过了前两个条件的过滤后,就可以将 nums[i]
与其该放置的位置 nums[nums[i] - 1]
的值交换,直到 nums[i] == nums[nums[i] - 1]
或者不满足前两个条件时,继续检查下一个元素。重复上述步骤直到数组遍历完。
最后,再对数组从头遍历,找到第一个与下标不对应的元素,此时 下标 + 1 即为目标解。若每一个都满足,那么缺失的正整数就为数组大小 + 1。
Code
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
if (nums.empty()) return 1;
for (int i = 0; i < nums.size(); ++i) {
while (nums[i] > 0 && nums[i] <= nums.size() && nums[nums[i] - 1] != nums[i]) {
int tmp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = tmp;
}
}
for (int i = 0; i < nums.size(); ++i) if (nums[i] != i + 1) return i + 1;
return nums.size() + 1;
}
};