**Input:** nums = [1,2,0]
**Output:** 3
**Input:** nums = [3,4,-1,1]
**Output:** 2
**Input:** nums = [7,8,9,11,12]
**Output:** 1
class Solution {
public int firstMissingPositive(int[] nums) {
// corner case
if (nums.length == 0) return 1;
// walk
for (int i = 0; i < nums.length; i++) {
// if (nums[i] <= 0 || nums[i] >= nums.length) continue;
while (nums[i] != i) {
if (nums[i] <= 0 || nums[i] >= nums.length || nums[nums[i]] == nums[i]) {
break;
} else {
int tmp = nums[i];
nums[i] = nums[nums[i]];
nums[tmp] = tmp;
}
}
}
// final check
int res = -1;
for (int i = 0; i < nums.length; i++) {
if (i == nums.length - 1 || nums[i+1] != i+1) {
res = i + 1;
break;
}
}
res = nums[0] == res ? res + 1 : res; // don't forget nums[0], might equals to result
// result
return res;
}
}
/*
walk
if nums[i] <= 0 or nums[i] >= length, continue
while nums[i] != i swap:
if nums[nums[i]] == nums[i], nums[nums[i]] = -1
else swap i, nums[i]
final check:
if nums[i+1] != i+1, break, return i+1.
*/
class Solution {
public int firstMissingPositive(int[] nums) {
// edge cases
if (nums == null || nums.length == 0) return 1;
for (int i = 0; i < nums.length; i++) {
while (nums[i] != i
&& nums[i] >= 0 && nums[i] < nums.length
&& nums[i] != nums[nums[i]]) {
int tmp = nums[i];
nums[i] = nums[tmp];
nums[tmp] = tmp;
}
}
int i = 1;
for (; i < nums.length; i++) {
if (nums[i] != i) return i;
}
if (nums[0] == i) i++;
return i;
}
}