給你一個未排序的整數數組,請你找出其中沒有出現的最小的正整數。
示例 1:
輸入: [1,2,0]
輸出: 3
解題思路:
- 判斷數組中是否存在1,如果沒有1則直接返回1,結束;
- 如果數組長度爲1,同時數組中存在1,則直接返回2,結束;
- 將數組中小於1或者大於數組長度length的數變爲1;
- 根據nums[i]的值將nums[nums[i]]對應的數變爲負數,表示數組中存在該正數;因爲nums[i]的值可能超過數組邊界,因此當nums[i]=length時,使nums[0]變爲負數;
- 遍歷數組,當數組中某一個位置的值爲正數,表示數組中缺少該位置值的整數,返回該位置的index,結束;注意nums[0]表示的是數組中是否存在length這個正數;
- 如果數組全爲負數,則返回length+1,結束;
# Python3
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
if not nums: # 如果數組爲空,返回1
return 1
length = len(nums) # 計算數組的長度
if 1 not in nums: # 如果1不在數組中,返回1
return 1
if length == 1: # 如果1在數組中,同時數組長度爲1,則直接返回2
return 2
for i in range(length): # 數組中存在1,同時將小於1或者大於數組長度的值變爲1
if nums[i]<=0 or nums[i]>length:
nums[i] = 1
# 將nums[i]對應的nums[nums[i]]變爲負數,表示nums中存在nums[i]整數
# 因爲nums[i]可能等於length,這超出了數組的範圍,因此當nums[i]==length時,令nums[0]變爲負數,nums[0]爲負數表示數組nums中存在length這個正數
for i in range(length):
temp = abs(nums[i])
if temp == length:
nums[0] = -abs(nums[0])
else:
nums[temp] = -abs(nums[temp])
# 遍歷數組,從1開始,如果存在nums[i]大於0,則直接返回1
for i in range(1,length):
if nums[i] > 0:
return i
# 判斷nums[0]是否大於零,因爲nums[0]爲負數表示數組中存在正數length
# 當nums[0]大於零時,則返回length
if nums[0]>0:
return length
# 如果數組中前length個整數都存在,則返回length+1這個正數
return length+1
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
if(nums.empty())
return 1;
int length = nums.size();
if(std::find(nums.begin(),nums.end(),1)==nums.end())
return 1;
if(length==1)
return 2;
for(int i=0;i<length;++i)
{
if(nums[i]<=0 || nums[i]>length)
nums[i] = 1;
}
for(int i=0;i<length;++i)
{
int temp = abs(nums[i]);
if(temp<length)
nums[temp] = -(abs(nums[temp]));
else
nums[0] = -(abs(nums[0]));
}
for(int i=1;i<length;++i)
{
if(nums[i]>0)
return i;
}
if(nums[0]>0)
return length;
return length+1;
}
};