128. Longest Consecutive Sequence
题目要求:
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
翻译一下:给出当前数组中最长的连续元素序列的长度
举个例子:
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
话不多说上代码
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums=set(nums)
res=0
for num in nums:
#find a start of each streak
if num-1 not in nums:
y=num+1
#start calculate the consecutive numbers
while y in nums:
y += 1
#get res' of each streak then get the larger one
res=max(res,y-num)
return res
思路:
来源于leetcode讨论区大神的思路
先将列表转化为set,此处在python中时间复杂度为O(n)
具体为什么可以看这 link
这个思路的妙就妙在它要先找出‘头’,当num-1不在该set中时,该num就是一个‘头‘。
接下来就看连续序列有多长,用一个while循环,如果num+1在set中,就继续,否则结束。
注意,走一次if就当作一次streak,那么每次结算新的res就在while结束后,if循环内。
最后返回res,也就是最大长度。
可能迷惑的点
该算法的时间复杂度为O(n),那么可能会想为什么for循环里嵌套了一个while并没有使时间复杂度增加呢?
因为while和for两个循环没有相关性。while循环一遍的时候,for没有从头开始,因此是O(m*n),也就是O(n)
以上都是一个很菜鸡的小白刷题心得,有错误之处还请批评指正,over。