国外html响应式网站模板,网络推广公司怎么报税,58和搜房那个网站做房产好,高端建筑材料有哪些题目内容#xff1a;
给定一个未排序的整数数组 nums #xff0c;找出数字连续的最长序列#xff08;不要求序列元素在原数组中连续#xff09;的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 #xff1a;
输入#xff1a;nums [100,4,200,1,3,…题目内容
给定一个未排序的整数数组 nums 找出数字连续的最长序列不要求序列元素在原数组中连续的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例
输入nums [100,4,200,1,3,2] 输出4 解释最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
答案
# codingutf-8
# 时间2024/3/7 19:52
# Pythonit教程网blog.pythonit.cn)
# Python全栈视频课件获取www.dqu.cc
# 加速高防cdnwoaiyundun.cn
def longestConsecutive(nums):if not nums:return 0# 使用集合存储数组中的元素以便进行快速查找num_set set(nums)longest_streak 0# 遍历集合中的每个元素for num in num_set:# 如果当前数字的前一个数字已经在集合中说明当前数字不是序列的起点# 跳过它因为我们已经处理过它作为序列的下一个数字if num - 1 in num_set:continue# 计算当前数字所在序列的长度current_num numcurrent_streak 1while current_num 1 in num_set:current_num 1current_streak 1# 更新最长序列长度longest_streak max(longest_streak, current_streak)return longest_streak# 示例
nums [100, 4, 200, 1, 3, 2]
print(longestConsecutive(nums)) # 输出应为 4