0.原题:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
翻译:在给定的未排序的、元素为整数的数组中,找出元素值连续的序列,输出最长的序列长度。要求O(n)复杂度。
1.代码:
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
list_length = len(nums)
if(not list_length):
return 0
counters = []
while(list_length):
archor = nums.pop()
counter = 1
#look forward
target = archor - 1
while(target in nums):
counter = counter + 1
nums.remove(target)
target = target - 1
#look backward
target = archor + 1
while(target in nums):
counter = counter + 1
nums.remove(target)
target = target + 1
counters.append(counter)
list_length = list_length - counter
return max(counters)
2.思路:
(1)首先需要判断list是否为空。
这一步是必须的,否则max()函数对空列表求值会报错。另外,由于if判断和while循环都用到了nums列表的长度,所以的设置一个参数记录这一值,即list_length = len(nums)。
注意,不要在while循环中反复计算nums列表长度,即while(len(nums)),这样会增加计算量,最终程序会因超时无法通过。
(2)读入一个元素,并判断在nums中,与这个元素相邻元素的个数。
step1:从nums中弹出一个值,记为anchor;
step2:不断地向前找连续的值,即是否存在anchor-1,anchor-2,anchor-3……,找到一个,counter就+1,直到找不到连续的值为之;
step3:向后找连续的值,并做counter+1操作。最后,把counter值记录下来。
在寻找的过程中,为了减少重复操作,对于查找完的值,要及时从nums中删除。
(3)找出最长连续序列的长度
由于每一步的counter值都记录在counters中,所以只要求解max(counters),即可得到最终解。
3.LeetCode结果