LeetCode-41. First Missing Positive
原创
©著作权归作者所有:来自51CTO博客作者ReignsDu的原创作品,请联系作者获取转载授权,否则将追究法律责任
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
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.
题解:
把每个nums[i]放在nums[nums[i] - 1]位置上,比如1放在nums[0], 2放在nums[1]中,类推,然后找到第一个num[i]不等于i + 1的值,i + 1即为缺失值,若都存在,那么n+1为第一个缺失的,注意处理0值和大于数组长度的值。
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
if (nums.empty() == true) {
return 1;
}
int n = nums.size();
for (int i = 0; i < n; i++) {
while (nums[i] > 0 && nums[i] < n && nums[nums[i] - 1] != nums[i]) {
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;
}
};