41. First Missing Positive
class Solution {
public int firstMissingPositive(int[] nums) {
int i = 0;
while(i<nums.length){
// switch the number at position i and nums[i]-1
// i.e. move the number at i to nums[i]-1;
if(nums[i]>0 && nums[i] <= nums.length && nums[i]!=nums[nums[i]-1]){
int temp = nums[i];
nums[i] = nums[nums[i]-1];
nums[temp-1] = temp;
}else{
i++;
}
}
for (int j = 0; j<nums.length; j++){
if(j+1 != nums[j]){
return j+1;
}
}
// if no number missing until the largest number in the array
return i+1;
}
}
Last updated
Was this helpful?