0
点赞
收藏
分享

微信扫一扫

First Missing Positive 寻找第一个缺失的整数,线性时间常量空间

楚木巽 2023-02-17 阅读 81


First Missing Positive


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.

class Solution {
public:

/* 这也能AC
int firstMissingPositive(vector<int>& nums) {

int len=nums.size();
int hash[10000];
memset(hash,0,sizeof(hash));
int i,max=-1;
for(i=0;i<len;i++)
{
if(nums[i]>0)
hash[nums[i]]=1;

if(nums[i]>max)
max=nums[i];
}

for(i=1;i<=max;i++)
{
if(hash[i]==0)
break;
}
return i;
}*/

//通过交换 将数放到正确的位置上
//A[i]放置第i+1的数 ; A[i]!=i,swap(A[A[i]], A[i]),一直合适为止
int firstMissingPositive(vector<int>& nums) {

int len=nums.size();
int i=0;

for(;i<len;)
{
//负数不匹配、len肯定有len个位置数、位置正确、交换的相等
if(nums[i]<=0 || nums[i]>len || nums[i]==i+1 || nums[i]==nums[ nums[i]-1 ])
i++;
else
swap(nums[i],nums[ nums[i]-1 ]);
}

for(i=0;i<len;i++)
if(nums[i]!=i+1)
break;

return i+1;
}

};

举报

相关推荐

0 条评论