题目
给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数。
示例 1:
输入: [1,2,0]
输出: 3
示例 2:
输入: [3,4,-1,1]
输出: 2
示例 3:
输入: [7,8,9,11,12]
输出: 1
方案:快排后遍历(快排复杂度高了,不行)
class Solution {
public int firstMissingPositive(int[] nums) {
Arrays.sort(nums);
if(nums.length==0||nums[0]>1)return 1;
int tmp=1;
for(int i=0;i<nums.length;i++){
if(nums[i]==tmp){tmp++;}
else if(nums[i]>tmp) return tmp;
}
return nums[nums.length-1]<0?1: nums[nums.length-1]+1;
}
}
方案2:构造Hash数组
class Solution {
public int firstMissingPositive(int[] nums) {
int len = nums.length-1;
int res = 0;
int tmp = 0;
while (res <= len) {
if (nums[res] == res + 1) {
res++;
}else{
tmp = nums[res];
if (tmp>len+1||tmp<res+1||nums[tmp-1] == tmp){
nums[res]=nums[len--];
}else {
nums[res] = nums[tmp-1];
nums[tmp-1] = tmp;
}
}
}
return res+1;
}
}
复杂度计算
- 时间复杂度:快排O(nlogn)+遍历O(n)=O(nlogn);
- 空间复杂度:O(1)