![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a5759dad457f8180bbe30568af8a69fc.png)
解法:原地哈希法
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8891136d37b5841c359de79df64e0308.png)
Java
class Solution {
public int firstMissingPositive(int[] nums) {
if(nums.length == 0) return 1;
for(int i=0; i<nums.length; i++) {
while(nums[i] >= 1 && nums[i] <= nums.length && nums[nums[i]-1] != nums[i]) {
int tmp = nums[nums[i]-1];
nums[nums[i]-1] = nums[i];
nums[i] = tmp;
}
}
for(int j=0; j<nums.length; j++) {
if(nums[j] != j+1)
return j+1;
}
return nums.length +1;
}
}
Python
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 1
for i in range(len(nums)):
while nums[i] >= 1 and nums[i] <= len(nums) and nums[nums[i]-1] != nums[i]:
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
for i in range(len(nums)):
if nums[i] != i+1:
return i+1
return len(nums)+1
参考
LeetCode题解