美文网首页leetcode
leetcode 最长连续序列 python

leetcode 最长连续序列 python

作者: DaydayHoliday | 来源:发表于2019-04-17 20:12 被阅读0次

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

    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))
    

    相关文章

      网友评论

        本文标题:leetcode 最长连续序列 python

        本文链接:https://www.haomeiwen.com/subject/afsowqtx.html