题目描述
Given an unsorted integer array, find the smallest missing positive integer.
对于给定的未经排序的array,找出第一个缺失的正整数。
例子
Input: [1,2,0]
Output: 3
Input: [3,4,-1,1]
Output: 2
Input: [7,8,9,11,12]
Output: 1
1. t i m e : O ( n l o g ( n ) ) , s p a c e : O ( 1 ) time:O(nlog(n)) , space:O(1) time:O(nlog(n)),space:O(1)
这种思路想法比较简单,先给数组排个序,比较nums[i]和nums[i+1]
的差值,大于1则返回nums[i]
.思路是很简单,但是实现起来有些烦,并不通用,测试也不能通过,所以切忌眼高手低。
错误代码,对于**[1,2,0]、[1,4,0]**这类测试样例均不能通过
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
print(nums)
for i in range(len(nums)):
if nums[i]+1!=nums[i+1]:
# print(nums[i]+1)
break
else:
print(1)
# break
return nums[i]+1
另外一种巧妙地方式:
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
res = 1
for num in nums:
if num == res:
res = res + 1
print(res)
return res
Runtime: 28 ms, faster than 44.80% of Python online submissions for First Missing Positive.
Memory Usage: 11.8 MB, less than 45.43% of Python online submissions for First Missing Positive.
2. t i m e : O ( n ) , s p a c e : O ( n ) time:O(n) , space:O(n) time:O(n),space:O(n)
这种方法是先去除掉原数组中小于0的元素,对于保留的元素,将其根据其值大小映射到另外一个数组中用1标示,tmp_arr[n-1] = 1
,但是原题中要求的是常数级的空间开销,所以提交不通过。
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for num in nums:
if num<=0:
nums.remove(num)
# print(nums)
if nums == []:
return 1
count = max(nums)
tmp_arr = [0]*count
for n in nums:
tmp_arr[n-1] = 1
#print(tmp_arr)
for i in range(len(tmp_arr)):
if tmp_arr[i]==0:
#print(i+1)
return i+1
return count+1
3. t i m e : O ( n ) , s p a c e : O ( 1 ) time:O(n) , space:O(1) time:O(n),space:O(1)
这里还没搞清楚为什么那句只能用while
不能用if
,起床了再来想。
因为这里如果使用if那么只会对交换之前的值进行判断,交换之后就结束了,但是对于while
而言,他需要判断所有交换后的结果是否仍满足此条件
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
L = len(nums)
if L == 0:
return 1
for i in range(L): #设定规则
if nums[i]>0: #这个if语句可以删去,可以减少空间开销,而加上则可以减少时间开销
while(0<nums[i]<L+1 and nums[nums[i]-1]!=nums[i]):#注意这里只能是while不可以是if
tmp = nums[nums[i]-1]
nums[nums[i]-1] = nums[i]
nums[i] = tmp
#print(nums) #[-1, 1, 3, 4]
for i in range(L): #验证不符合规则的点
if nums[i]!=i+1:
#print(i+1)
return i+1
#print(L+1)
return L+1 #[1,2,3,4,5]全部符合
Runtime: 12 ms, faster than 99.87% of Python online submissions for First Missing Positive.
Memory Usage: 11.8 MB, less than 30.33% of Python online submissions for First Missing Positive.