您的位置:首页 > 产品设计 > UI/UE

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

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: