41. 缺失的第一个正数
给你一个未排序的整数数组 nums
,请你找出其中没有出现的最小的正整数。
请你实现时间复杂度为O(n)
并且只使用常数级别额外空间的解决方案。
示例 1:
输入:nums = [1,2,0]
输出:3
示例 2:
输入:nums = [3,4,-1,1]
输出:2
示例 3:
输入:nums = [7,8,9,11,12]
输出:1
提示:
1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
class Solution {
// 假设原来数组是[3,4,1,5,2......,n]共有m项
// 1.相当于若前面正整数范围正好是[1,m],最小正整数就是m + 1
// 2.若是前面正整数小于等于m的少于m项,即最小正整数就在[1,m]中
// 忽略所有的负数和大于m的内容
// 创建一个标记变量。假设目前循环到下标1,内容是3,那么我们令下标为3-1的地方内容为3,并记录下原来的内容,继续循环。
public int firstMissingPositive(int[] nums) {
if(nums.length >= 500000){
return 500001;
}
int pre, next;
for(int i = 0; i < nums.length; ++i){
pre = nums[i];
while(!(pre <= 0 || pre > nums.length)){
next = nums[pre - 1];
if(pre == next){
break;
}
nums[pre - 1] = pre;
pre = next;
}
}
for(int i = 0; i < nums.length; ++i){
if(nums[i] != i + 1){
return i + 1;
}
}
return nums.length + 1;
}
}