LeetCode Hard 128最長連続サブシーケンスPython


def longestConsecutive(self, nums):
    """
    Solution Method
      :  
      :
                   ,   nums     ,           O1
              nums    num              ,   while             ,
                   ,                             ,      
          ,    
    """
    num_set = set(nums)
    ans = 0
    for num in nums:
        if num - 1 in num_set:
            continue
        curr = num + 1
        curr_longest = 1
        while curr in num_set:
            curr_longest += 1
            curr += 1
        ans = max(ans, curr_longest)
    return ans
def longestConsecutiveX(self, nums):
    """
    My TLE Method
      66/68 case,  TLE ,TLE             while      while
                        ,         3,   record[3] = 1,    
      num+1    num-1               ,     3             
       5 ,3           ,      3 ,  3                 
      1 3,  3         5+3+1,        ,     while         max
          ,                                   ,      
    """
    record = dict()
    ans = 0
    for num in nums:
        if num in record and record[num] != 0:
            continue
        record[num] = 1
        sub_max = 0
        sub = num - 1
        while sub in record and record[sub] != 0:
            sub_max = max(sub_max, record[sub])
            sub = sub - 1
        top = num + 1
        top_max = 0
        while top in record and record[top] != 0:
            top_max = max(top_max, record[top])
            top = top + 1
        record[num] += (top_max + sub_max)
        if num - 1 not in record:
            record[num - 1] = 0
        if num + 1 not in record:
            record[num + 1] = 0
        ans = max(ans, record[num])

    return ans