leetcode

leetcode 最长连续序列 python

2019-04-17  本文已影响0人  DaydayHoliday

维护两个字典,一个字典记录某数的前序序列,一个记录后续序列
应该还有优化空间

class Solution(object):
    def longestConsecutive(self, nums):
        if len(nums)==0:
            return 0
        up_dict={}
        down_dict={}
        for num in nums:
            if num in up_dict:
                continue
            if num-1 in up_dict:
                up_left=up_dict[num-1][0]
                up_dict[num]=[up_left,num]
            else:
                up_dict[num]=[num,num]
            if num+1 in down_dict:
                down_right=down_dict[num+1][1]
                down_dict[num]=[num,down_right]
            else:
                down_dict[num]=[num,num]
            down_dict[up_dict[num][0]]=[up_dict[num][0],down_dict[num][1]]
            up_dict[down_dict[num][1]]=[up_dict[num][0],down_dict[num][1]]
        def count_seq(num):
            return up_dict[num][1]-up_dict[num][0]+down_dict[num][1]-down_dict[num][0]+1
        return max(map(count_seq,nums))
上一篇下一篇

猜你喜欢

热点阅读