First Missing Positive
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.
分析:寻找第一个Missing的正整数。
题意:题目需要给定的数组A在排序后满足:A[i] 等于 i+1 。
算法:不要使用基于比较的各种排序,可以使用计数排序和桶排序,我尝试了桶排序,虽然增加了额外的空间,但是题目要求并没有那么严格,通过了。
大空间消耗的代码:
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int`] :rtype: int """ SIZE = 40 DIVID = 10000 buckets = [None] * SIZE for value in nums: if value > 0: index = value * SIZE / DIVID self.insertToBucket(buckets, index, value) is_first = True res = [] for b in buckets: if b: while b: res.append(b.val) b = b.next if len(res) == 0: return 1 elif len(res) == 1: if res[0] == 1: return 2 else: return 1 else: pre = res[0] if pre != 1: return 1 for i in res[1:]: if i != pre: if i - pre != 1: return pre + 1 else: pre = i if res[0] == 1: return i + 1 else: return res[0] - 1 def insertToBucket(self, buckets, index, value): p = head = buckets[index] if head is None: buckets[index] = ListNode(value) elif p and value < p.val: buckets[index] = ListNode(value) buckets[index].next = p else: while p and value >= p.val: pre = p p = p.next if p is None: pre.next = ListNode(value) else: pre.next = ListNode(value) pre = pre.next pre.next = p def outputList(self, l): l_p = l while l_p: print l_p.val, l_p = l_p.next print
O(1)空间的代码:
class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int`] :rtype: int """ nums_len = len(nums) if not nums_len: return 1 for i in range(nums_len): while nums[i] != i + 1: if nums[i] <= 0 or nums[i] >= nums_len or nums[i] == nums[nums[i] - 1]: break k = nums[i] nums[i], nums[k - 1] = nums[k - 1], nums[i] for i, v in enumerate(nums): if v != i + 1: return i+1 return i + 2