zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):128-Longest Consecutive Sequence

    题目来源:

      https://leetcode.com/problems/longest-consecutive-sequence/


    题意分析:

      给定一个没有排好序的数组,找到最长的连续序列的长度。要求时间复杂度是O(n)。比如[100, 4, 200, 1, 3, 2],其最长长度是[1,2,3,4]长度为4.


    题目思路:

      对于每个数记录他所在的目前最长的序列,将其±1,如果其也在给定序列中,那么更新他所在的最长序列,比如上面的例子。所对应的序列变化是:

    1. 100:[100,100];

    2.100:[100,100];4:[4,4];

    3.100:[100,100];4:[4,4];200:[200,200];

    4.100:[100,100];4:[4,4];200:[200,200];1:[1,1];

    5. 100:[100,100];4:[3,4];200:[200,200];1:[1,1];3 :[3,4];

    6.100:[100,100];4:[1,4];200:[200,200];1:[1,4];3 :[3,4],2:[1,2];

    所以得到答案是4


    代码(python):

      

     1 class Solution(object):
     2     def longestConsecutive(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: int
     6         """
     7         count = {}
     8         ans = 0
     9         if len(nums) != 0: ans = 1
    10         for i in nums:
    11             #ans = max(ans,1)
    12             if i in count: continue
    13             count[i] = [i,i]
    14             if i - 1 in count:
    15                 #print(i - 1,count[i - 1])
    16                 count[count[i - 1][0]][1],count[i][0] = count[i][1],count[i - 1][0]
    17                 #print(count[i - 1][0],count[count[i - 1][0]],i,count[i])
    18                 ans = max(ans,count[count[i - 1][0]][1] + 1 - count[count[i - 1][0]][0])
    19             if i + 1 in count:
    20                 #print(i + 1,count[i + 1])
    21                 count[count[i + 1][1]][0],count[count[i][0]][1] = count[i][0],count[i+1][1]
    22                 ans = max(ans,count[count[i + 1][1]][1] - count[count[i + 1][1]][0] + 1)
    23                 #print(count[i + 1][1],count[count[i + 1][1]],count[i][0],count[count[i][0]])
    24         #for i in count:
    25             #print(i,count[i])
    26             #ans = max(ans,count[i][1] - count[i][0] + 1)
    27         return ans
    28             
    View Code
  • 相关阅读:
    java后台保存JSON
    查询树节点及其所有上级节点sql语句
    查询树节点及其所有下级节点sql语句
    Hibernate查询机制使用原生sql语法查询
    SSH框架通过poi导出excel表格
    java通过poi导入excel数据
    各类型日期date的相互转化
    推荐一下我喜欢的软件
    青岛市赛总结——远征石油大学
    My learn of git
  • 原文地址:https://www.cnblogs.com/chruny/p/5306877.html
Copyright © 2011-2022 走看看