// @lc code=start
class Solution {
public int firstMissingPositive(int[] nums) {
int size = nums.length;
for(int i = 0; i < size; i++){
int ind = nums[i] - 1;
// 当对应元素nums[ind] - 1 == ind 时无需处理,eg.[1,2,3]
if(i == ind)
continue;
// ind < 0 || ind >= size : 当元素值超出[0,nums.length)时即认为ind对应位置元素不存在
// nums[ind] == nums[i] : 当对应位置 ind已经存在元素则当前i位置设为不存在
if(ind < 0 || ind >= size || nums[ind] == nums[i]){
nums[i] = Integer.MIN_VALUE;
continue;
}
// 交换元素
int temp = nums[ind];
nums[ind] = nums[i];
nums[i] = temp;
// 再次遍历当前i索引
i--;
}
// 返回第一个元素值为Integer.MIN_VALUE的位置 + 1
for(int i = 0; i < size; i++)
if(nums[i] == Integer.MIN_VALUE)
return i + 1;
// 如果全部不为Integer.MIN_VALUE 则 直接返回 size + 1
// eg.[1,2,3,4,5] return 6
return size + 1;
}
}
// @lc code=end