您的位置:首页 > 编程语言 > Python开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: