给定一个未排序的整数数组,找出其中没有出现的最小的正整数。
示例 1:
输入: [1,2,0]
输出: 3
示例 2:
输入: [3,4,-1,1]
输出: 2
示例 3:
输入: [7,8,9,11,12]
输出: 1
解题思路
python代码的思路类似于“抽屉原理”,有些地方也叫“鸽巢原理”,就是将每个人放到属于
他自己的位置上,如果没有位置说明这个人不是一家人。这就是鸽巢原理
就好比这题,他需要找到缺失的第一个正数,那么我将每个正数放到对应的索引位置上,
如果某个数大于最大索引位置,说明没有他的位置,直接跳过。
举个例子
1, 6, 3,5
1 就在自己的位置上,跳过
6 没有位置,暂时跳过,一会别人过来替换掉它
3 放到5所在的位置中,将5拿出来,继续判断
5 发现没有他的位置。
最后从头遍历一波,发现数和位置不对应的,就是这个位置缺人了。
说明,python代码是我最开始想到的思路,不够完美,将这个位置置为None,代表这个位置有人了。
将一个数找到位置后,继续将原此位置的人拉出来,给他找位置,知道出现一个没有位置的人。就结束。
Python
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
length = len(nums)
if length == 1:
return 2 if nums[i] == 1 else 1
while i < length:
if nums[i] is None or nums[i] > length or nums[i] < 1:
i += 1
continue
y = nums[i] - 1
while nums[y] is not None:
h = nums[y]
nums[y] = None
if h is None or h > length or h < 1:
break
y = h - 1
i += 1
for i in range(length):
if nums[i] is not None:
return i + 1
return length + 1
java代码借鉴了别人对鸽巢原理的见解做了自己的实现
Java
class Solution {
public void swap(int[] nums, int i, int j){
nums[i] = nums[i] + nums[j];
nums[j] = nums[i] - nums[j];
nums[i] = nums[i] - nums[j];
}
public int firstMissingPositive(int[] nums) {
for(int i = 1; i < nums.length;i++){
while(nums[i] != i + 1 && nums[i] > 0 && nums[i] < nums.length&&nums[nums[i] - 1] != nums[i]){
this.swap(nums, nums[i] -1, i);
};
}
for (int i=0;i
if(nums[i] != i+1){
return i+1;
}
}
return nums.length + 1;
}
}