题目:
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.
思路:
这个题难在 需要用 O(N)的时间复杂度,和 O(1)的空间复杂度。看了讨论中的一个解决方案。神仙思路
1、首先对区间 (1,n)以外的数字,改为0
2、用当前数组的index,记录(1,n)区间内有什么数字。【ps:这里用当前数组,需要保持原始信息,即这个元素存储的数字,又要能体现出这个index是否在数组中,作者用 nums[nums[i]%len(nums)] += len(nums) 来实现,>= len(nums) 表示这个index存在在原始数组中,同时保证后面取nums[i] ,这个值依旧被保留】
答案:
def firstMissingPositive(self, nums: List[int]) -> int:
nums.append(0)
for i in range(len(nums)):
if nums[i]<0 or nums[i]>=len(nums):
nums[i] = 0
for i in range(len(nums)):
nums[nums[i]%len(nums)] += len(nums) #我真的是震惊,厉害!
for i in range(len(nums)):
if nums[i]//len(nums) < 1:
return i
return len(nums)