leetcode @python 128. Longest Consecutive Sequence
2016-04-03 11:14
519 查看
题目链接
https://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.
题目大意
给定一个序列,返回最长的连续子序列解题思路
依次遍历序列中的数,使用栈将数和与此数相连的数放进栈(如果这些数在序列中出现),返回栈的最大长度代码
class Solution(object): def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ nums = set(nums) res = 0 while nums: stack = [next(iter(nums))] tmp = 0 while stack: tmp += 1 curr = stack.pop() nums.discard(curr) if curr - 1 in nums: stack.append(curr - 1) if curr + 1 in nums: stack.append(curr + 1) res = max(res, tmp) return res
相关文章推荐
- leetcode @python 127. Word Ladder
- python中的operator库
- 如何配置OPENCV的Python接口
- Python基础之数据类型
- java和python对比
- python的注释
- Python之路【第十八篇】Django小项目简单BBS论坛部分内容知识点
- python中的字符串
- python中yaml模块的使用
- Python3使用requests模块显示下载进度
- Python及bs4、lxml、numpy模块包的安装
- python3 发送邮件功能
- python魔法 交换两个数字
- python 中斐波那契数列的那些事
- python快速排序
- Python 模块动态加载技术
- Python2.6.6执行selenium自动化
- TensorFlow 简明教程(python版)
- Python producer & consumer model
- Python multiprocessing threading