一.问题描述
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
给定一组integers,找出其中最小的缺失的正整数值,要求时间复杂度为O(n),空间复杂度为O(1)。
二.代码编写
时间复杂度为O(n)意味着不能直接对list进行排序O(NlogN),空间复杂度为常数意味着不能新建一个list。
常数空间,我们应该想到直接swap,将相应得到数字m放到list的(m-1)的位置上。全部交换完毕后,返回list中第一个不满足nums[m]!=m+1的(m+1)值。
代码如下:
'''
@2016.11.20 by wttttt
@ for problem details, see https://leetcode.com/problems/first-missing-positive/
@ for solution description,see
@ trick
'''
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return 1
len_nums = len(nums)
i = 0
while i< len_nums:
if nums[i]!=i+1 and nums[i]<=len_nums and nums[i]>0:
#nums[i],nums[nums[i]-1] = nums[nums[i]-1],nums[i] # swap
tmp = nums[i]
if tmp == nums[tmp-1]:
i += 1
continue
nums[i] = nums[tmp-1]
nums[tmp-1]=tmp
else:
i += 1
for i in range(len_nums):
if nums[i] != i+1:
return i+1
return nums[-1]+1