题目
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.
思路一
先找到最大值,建立 hashtable 记录是否存在。
class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<=0)
return 1;
int max = 0;
for(int i=0;i<n;i++)
{
if(A[i]>max)
max = A[i];
}
vector<bool> table(max+1,false);
for(int i=0;i<n;i++)
{
if(A[i]>0)
table[A[i]]=true;
}
int i=1;
while(i<=max)
{
if(table[i]==false)
return i;
i++;
}
if(i>max)
return max+1;
}
};
优化代码
class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<=0)
return 1;
vector<bool> table(n+1,false);
for(int i=0;i<n;i++)
{
if(A[i]>0 && A[i]<=n)
table[A[i]]=true;
}
int i=1;
while(i<=n)
{
if(table[i]==false)
return i;
i++;
}
return n+1;
}
};
思路二: O(N) time and O(1) space
class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<=0)
return 1;
int i=0;
while(i<n)
{
if(A[i]>0 && A[i]<n && A[i]-1!=i && A[A[i]-1]!=A[i])
{
int tmp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = tmp;
}
else
i++;
}
int j=0;
while(j<n && A[j]-1==j)
j++;
if(j<n)
return j+1;
return n+1;
}
};
最新 java
public class Solution {
public int firstMissingPositive(int[] nums) {
if(nums == null || nums.length == 0){
return 1;
}
Set<Integer> hashset = new HashSet<>();
for(int i=0; i<nums.length; i++){
hashset.add(nums[i]);
}
int index = 1;
while(hashset.contains(index)) {
index++;
}
return index;
}
}