-
Notifications
You must be signed in to change notification settings - Fork 0
41. First Missing Positive
Linjie Pan edited this page Apr 9, 2019
·
1 revision
The idea is simple: put the positive integer n
(n > 0
and n <= array.length
) at index n - 1
. Then traverse the array, if nums[index] != index + 1
, then we find the first miss positive number.
public int firstMissingPositive(int[] nums) {
for(int i = 0; i < nums.length; i++) {
while( nums[i] > 0 && nums[i] <= nums.length ) {
int temp = nums[nums[i] - 1];
if( temp == nums[i] ) // If nums[nums[i] - 1] equals nums[i], then we don't need to exchange them
break;
nums[nums[i] - 1] = nums[i];
nums[i] = temp;
}
}
for(int i = 0; i < nums.length; i++)
if( nums[i] != i + 1 )
return i + 1;
return nums.length + 1;
}