题:https://leetcode.com/problems/longest-consecutive-sequence/description/
题目
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
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.
思路
两种方式
1.
利用sort先对nums进行排序,然后遍历一次,如果当前遍历的和上次访问的数据相同则跳过,否则,若当前数据比上次访问的数据大一,则不同。
2.
利用 set对nums进行set操作。
Solution
https://leetcode.com/problems/longest-consecutive-sequence/solution/
code
1.
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
nums.sort()
longest_streak = 1
current_streak = 1
for i in range(1,len(nums)):
if nums[i]!=nums[i-1]:
if nums[i] == nums[i-1]+1:
current_streak +=1
else:
longest_streak = max(longest_streak,current_streak)
current_streak =1
return max(longest_streak,current_streak)
2.
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
longest_streak = 0
numsset = set(nums)
for num in nums:
if num-1 not in numsset:
current_num = num
current_streak = 1
while current_num + 1 in numsset:
current_num +=1
current_streak +=1
longest_streak = max(longest_streak,current_streak)
return longest_streak