leetcode第128题最长连续数列

 要求时间复杂度O(n)其实思路比较简单,维护一个区间的集合(用的dict),如果当前扫描的数在集合中能够与某一个区间接壤(向前或向后):合并区间

扫描当前数字

如果出现过了:不管;

如果没出现过:

        如果不与集合中的区间接壤,新增新区间,起始位置为当前元素,长度为0

        如果与某个区间的前边界(或/和)后边界接壤,合并此元素和区间

        

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        dict_int={}
        dict_head={}
        dict_end={}
        """
        if len(nums)<2:return len(nums)
        set_int=set()
        dict_head={}
        dict_end={}
        ans=1
        for i in range(len(nums)):
            if nums[i] not in set_int:
                set_int.add(nums[i])
                temp_a=dict_end.has_key(nums[i]-1)
                temp_b=dict_head.has_key(nums[i]+1)
                sum=temp_a*2+temp_b
                if sum==2:
                    dict_head[nums[i]-1-dict_end[nums[i]-1]]+=1
                    dict_end[nums[i]]=temp_2=dict_end.pop(nums[i]-1)+1
                    ans=max(ans,temp_2+1)
                elif sum==1:
                    dict_end[nums[i]+1+dict_head[nums[i]+1]]+=1
                    dict_head[nums[i]]=temp_1=dict_head.pop(nums[i]+1)+1
                    ans=max(ans,temp_1+1)
                elif sum==0:
                    dict_head[nums[i]]=0
                    dict_end[nums[i]]=0
                else:
                    last_len=dict_head.pop(nums[i]+1)+1
                    pre_len=dict_end.pop(nums[i]-1)+1
                    dict_head[nums[i]-pre_len]=dict_end[nums[i]+last_len]=last_len+pre_len
                    ans=max(ans,last_len+pre_len+1)
        return ans

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值