Topic: https://leetcode-cn.com/problems/first-missing-positive/
Reference: https://leetcode-cn.com/problems/first-missing-positive/solution/que-shi-de-di- yi-ge-zheng-shu-
by-leetcode / reference 2: https://leetcode-cn.com/problems/first-missing-positive/solution/tong-pai-xu-python-dai-ma-by-liweiwei1419 /
given an unsorted array of integers, find the smallest positive integer which does not arise.
The official submission orz
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
/*
*给定一个未排序的整数数组,找出其中没有出现的
*最小的正整数。要求时间复杂度O(n),空间复杂度
*O(1).
*/
int n = nums.size();
int pos = -1;
for(int i = 0;i < n;i++) {
if(nums[i] == 1) {
pos = i;
break;
}
}
if(pos == -1) return 1;
//确保有1的前提下,将非法数变为1
for(int i = 0;i < n;i++) {
if(nums[i] <= 0 || nums[i] > n) nums[i] = 1;
}
//nums[i] < 0表示i存在
for(int i = 0;i < n;i++) {
int x = nums[i];
if(x < 0) x = -x;
if(nums[x-1] > 0) nums[x-1] = -nums[x-1];
}
for(int i = 0;i < n;i++) {
if(nums[i] > 0) return i+1;
}
return n+1;
}
};
Method 2: Using the principle Drawer
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
/*
*给定一个未排序的整数数组,找出其中没有出现的
*最小的正整数。要求时间复杂度O(n),空间复杂度
*O(1).
*/
int n = nums.size(),pos;
for(int i = 0;i < n;i++) {
while(nums[i] != i+1) {
if(nums[i] <= 0 || nums[i] > n ||nums[nums[i]-1] == nums[i])
break;
pos = nums[i]-1;
swap(nums[i],nums[pos]);//将nums[i]放到原本的地方
}
}
for(int i = 0;i < n;i++) {
if(nums[i] != i+1)
return i+1;
}
return n+1;
}
};