zoukankan      html  css  js  c++  java
  • [leetcode]Longest Consecutive Sequence @ Python

    原题地址:https://oj.leetcode.com/problems/longest-consecutive-sequence/

    题意:

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

    For example,
    Given [100, 4, 200, 1, 3, 2],
    The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

    Your algorithm should run in O(n) complexity.

    解题思路:使用一个哈希表,在Python中是字典dict数据类型。dict中的映射关系是{x in num:False},这个表示num中的x元素没有被访问过,如果被访问过,则为True。如果x没有被访问过,检查x+1,x+2...,x-1,x-2是否在dict中,如果在dict中,就可以计数。最后可以求得最大长度。

    代码:

    class Solution:
        # @param num, a list of integer
        # @return an integer
        def longestConsecutive(self, num):
            dict = {x: False for x in num} # False means not visited
            maxLen = -1
            for i in dict:
                if dict[i] == False:
                    curr = i+1; lenright = 0
                    while curr in dict:
                        lenright += 1; dict[curr] = True; curr += 1
                    curr = i-1; lenleft = 0
                    while curr in dict:
                        lenleft += 1; dict[curr] = True; curr -= 1
                    maxLen = max(maxLen, lenleft+1+lenright)
            return maxLen
  • 相关阅读:
    算法作业实验三
    牛客练习赛53 B 美味果冻
    牛客练习赛53 C 富豪凯匹配串
    bitmat
    牛客挑战赛33 B 鸽天的放鸽序列
    树状数组
    线段树
    2019牛客国庆集训派对day7 A 2016
    背包
    作业三 -并查集
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3765546.html
Copyright © 2011-2022 走看看