def longest_consecutive(nums): if not nums: return 0 转为集合,便于O(1)时间判断元素是否存在 num_set = set(nums) max_length = 0 for num in num_set: 只从连续序列的起点开始计算(即num-1不在集合中) if num - 1 not in num_set: current_num = num current_length = 1 while current_num + 1 in num_set: current_num += 1 current_length += 1 max_length = max(max_length, current_length) return max_length print(longest_consecutive([100, 200, 1, 2, 3, 90, 4]))
点赞 评论

相关推荐

有了offer来还愿:学校不行,专业不行,学历不行,怎么找?
点赞 评论 收藏
分享
10-02 19:29
已编辑
浙江科技大学 运营
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务