LeetCode题目记录
第128题:最长连续序列
1.题目链接
[https://leetcode-cn.com/problems/longest-consecutive-sequence/submissions/]
2.题目内容
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
3.解题思路
本题需求出未排序整数数组nums中最长连续序列的长度。
(乙)
先判断数组nums中的元素个数是否为0或1,当个数为0时,输出结果为0;当个数为1时,输出结果为1。如果元素个数大于1,则先将数组进行排序,将排序后的数组相邻两个数相减求得差分数组diff。当diff中连续为1(考虑到数字相同的情况,将用0连接的1也看作是连续的1)的元素个数最大为n时,返回的结果为n+1。(这种思路容易因为忽视一些细节导致错误)
4.代码实现
# 自己解法
#(甲)
#(乙)
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if len(nums)==0:
return 0
elif len(nums)==1:
return 1
else:
nums.sort()
diff = [nums[i+1]-nums[i] for i in range(len(nums)-1)]
res = []
re = 1
for i in range(len(diff)):
if diff[i]==1:
re+=1
if i==len(diff)-1:
res.append(re)
elif diff[i]==0:
if i==len(diff)-1:
res.append(re)
else:
res.append(re)
re = 1
return max(res)