leetcode -- Longest Consecutive Sequence -- 重点
2015-12-23 21:48
197 查看
https://leetcode.com/problems/longest-consecutive-sequence/
思路很简单。看/article/4981574.html
http://chaoren.is-programmer.com/posts/42924.html
code
另一个更简单的AC code
思路很简单。看/article/4981574.html
http://chaoren.is-programmer.com/posts/42924.html
code
class Solution(object): def longestConsecutive(self, num): """ :type nums: List[int] :rtype: int """ dict = {x:False for x in num} # False means not visited maxLen = -1 for i in dict: if dict[i] == False: curr = i + 1; len1 = 0 while curr in dict and dict[curr] == False: len1 += 1; dict[curr] = True; curr += 1 curr = i - 1; len2 = 0 while curr in dict and dict[curr] == False: len2 += 1; dict[curr] = True; curr -= 1 maxLen = max(maxLen, 1 + len1 + len2) return maxLen
自己重做
可以AC,但是这里没必要使用count。只用flag就行class Solution(object): def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 flag = {} count = {} for x in nums: if x not in flag: flag[x] = False if x in count: count[x] += 1 else: count[x] = 1 res = 0 for x in nums: if not flag[x]: flag[x] = True cur = x; sub_count = 0; for i in xrange(1, len(nums)): cur = x + i if cur in count: flag[cur] = True sub_count += 1 else: break cur = x for i in xrange(1, len(nums)): cur = x - i if cur in count: flag[cur] = True sub_count += 1 else: break sub_count += 1 res = max(res, sub_count) return res
另一个更简单的AC code
class Solution(object): def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 flag = { x:False for x in nums}#注意这里flag list comprehension的方法 res = 0 for x in nums: if not flag[x]: flag[x] = True cur = x + 1 len1 = 0 while cur in flag and flag[cur] == False: len1 += 1 flag[cur] = True#注意这个flag 要在cur += 1之前。 cur += 1 cur = x - 1 len2 = 0 while cur in flag and flag[cur] == False: len2 += 1 flag[cur] = True#注意这个flag 要在cur -= 1之前。 cur -= 1 #print len1, len2 res = max(res, len1 + len2 + 1) return res
相关文章推荐
- UIViewContentMode
- Error instantiating class with invalid types () or values ()
- 【leetcode题解】[E][52]303. Range Sum Query - Immutable
- TimesTen_创建序列(sequence)
- UICollectionViewCell
- UI01_UILabel
- 基于duilib的多标签简易浏览器
- UIView
- com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column 'rdate'
- 利用 druid 解析器解析SQL
- android125 zhihuibeijing 缓存
- leetcode -- Distinct Subsequences -- DP重点
- leetcode刷题日记——Implement Stack using Queues
- 三大GUI库——AWT、swing、SWT
- Android之UI圆角矩形,图形圆角美化
- 超级简单的UGUI血条制作技巧
- 关于easyUI在子页面增加显示tabs的一个问题
- KVO(NSKeyValueObserving)
- EasyUI Datebox 日期框
- UITableView 视觉差效果