Description
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
分析
题目的意思是:给定一个数组,找出最小的漏掉的正整数。
- 对每个正数,我们都交换到相应的位置,比如5,在数组中是第五个位置,则和第五个位置上的数进行交换。然后再遍历一遍找到第一个丢失的正整数。
nums=[3,4,-1,1] #交换前
nums=[1, -1, 3, 4] #交换后
C++实现
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n=nums.size();
for(int i=0;i<nums.size();i++){
while(nums[i]>0&&nums[i]<n&&nums[i]!=nums[nums[i]-1]){
swap(nums[i],nums[nums[i]-1]);
}
}
for(int i=0;i<nums.size();i++){
if(nums[i]!=i+1){
return i+1;
}
}
return n+1;
}
};
Python实现
class Solution:
def firstMissingPositive(self, nums):
nums_len = len(nums)
for i in range(nums_len):
while nums[i] > 0 and nums[i] <= nums_len\
and nums[nums[i]-1]!=nums[i]:
nums[nums[i]-1],nums[i] = nums[i],nums[nums[i]-1]
print(nums)
for i in range(nums_len):
if nums[i] != i + 1:
return i + 1
return nums_len + 1
if __name__ == "__main__":
solution=Solution()
nums=[3,4,-1,1]
res=solution.firstMissingPositive(nums)
print(res)