java
复制代码
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for(int i=0;i<n;i++){//确保1在0位置;2在1位置;3在2位置....
while(nums[i]>=1 && nums[i]<=n && nums[i]!=i+1 && nums[i]!=nums[nums[i]-1]){
swap(nums,i,nums[i]-1);
}
}
for(int j=0;j<n;j++){
if(nums[j]!=j+1){
return j+1;
}
}
return n+1;
}
public void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
java
复制代码
class Solution {
public int firstMissingPositive(int[] nums) {
Set<Integer> hash = new HashSet<>();
int n = nums.length;
for(int i=0;i<n;i++){
hash.add(nums[i]);
}
for(int j=1;j<=n;j++){
if(!hash.contains(j)){
return j;
}
}
return n+1;
}
}