Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

128. Longest Consecutive Sequence

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

Example 1:

1
2
3
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:

1
2
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

最大連續子字串,先排序,再看各值跟上個是不是差1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
T: O(n), S: O(n)
class Solution:class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if not nums: return 0
longest=current=1
nums=list(sorted(set(nums)))
print ("nums=",nums)
for i in range(1,len(nums)): # start from 1
if nums[i]==nums[i-1]+1:
current+=1
else: # not consecutive
longest=max(current,longest)
current=1
return max(current,longest)

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels