LeetCode----First Missing Positive
2015-09-09 19:50
281 查看
First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example,
Given
and
Your algorithm should run in O(n) time and uses constant space.
分析:
寻找第一个Missing的正整数。
题意:题目需要给定的数组A在排序后满足:A[i] 等于 i+1 。
算法:不要使用基于比较的各种排序,可以使用计数排序和桶排序,我尝试了桶排序,虽然增加了额外的空间,但是题目要求并没有那么严格,通过了。
大空间消耗的代码:
O(1)空间的代码:
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
相关文章推荐
- 文件遍历排序函数
- C#选择排序法实例分析
- C#插入法排序算法实例分析
- C#实现Datatable排序的方法
- SQLSERVER的排序问题结果不是想要的
- Windows Powershell排序和分组管道结果
- C#通过IComparable实现ListT.sort()排序
- C#选择法排序实例分析
- SQL学习笔记四 聚合函数、排序方法
- C#对list列表进行随机排序的方法
- 一根网线内的8根线哪4根是传输数据的,哪四根是防干扰的
- C#折半插入排序算法实现方法
- SQL进行排序、分组、统计的10个新技巧分享
- C++实现位图排序实例
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- SQL行号排序和分页(SQL查询中插入行号 自定义分页的另类实现)
- PHP下对数组进行排序的函数
- PHP数组排序之sort、asort与ksort用法实例
- php通过asort()给关联数组按照值排序的方法