[LintCode 124] 最长连续序列(Python)
来源:互联网 发布:php查询系统源码 编辑:程序博客网 时间:2024/06/03 14:50
问题描述
给定一个未排序的整数数组,找出最长连续序列的长度。
说明
样例
给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4
思路
用一个字典存储中间值。遍历数组,对于数字i,找到i-1和i+1对应的value值,如果不存在则记0。然后把i的value值设为i-1,i+1的value值之和,并加1,相当于连接起来。同时置最左端和最右端的数的value值为i的value值(中间的数都已经出现过,不会再用到了)。然后更新一次最大值。
代码
class Solution: """ @param: num: A list of integers @return: An integer """ def longestConsecutive(self, num): # write your code here if num is None or len(num) == 0: return 0 m = {} res = 0 for i in num: if i not in m: l = 0 r = 0 if i - 1 in m: l = m[i - 1] if i + 1 in m: r = m[i + 1] m[i] = 1 + r + l m[i + r] = 1 + r + l m[i - l] = 1 + r + l res = max(res, m[i]) return res
复杂度分析
时间复杂度
阅读全文
0 0
- [LintCode 124] 最长连续序列(Python)
- lintcode ----最长连续序列
- LintCode:最长连续序列
- LintCode-最长连续序列
- LintCode : 最长连续序列
- LintCode-最长连续序列
- lintcode--最长连续序列
- 最长连续序列-LintCode
- lintcode-最长连续子序列
- [Lintcode 397] 最长上升连续子序列(Python)
- LintCode--最长上升连续子序列
- lintcode-最长上升连续子序列-397
- 最长上升连续子序列(LintCode)
- LintCode- 最长上升连续子序列
- lintCode刷题--最长上升连续子序列
- LintCode:最长上升连续子序列
- *[Lintcode]Longest Consecutive Sequence最长连续序列
- lintcode -- 最长上升连续子序列
- Android 6.0 权限
- 链表拼接
- C和指针14章 预处理器笔记
- Spring中ClassPathXmlApplicationContext和ApplicationContext 的简单使用
- Java三大器之拦截器(Interceptor)的实现原理及代码示例
- [LintCode 124] 最长连续序列(Python)
- 数据结构改变
- [C专家]分析C语言声明——关于联合
- EventBus activity收不到post的消息原因分析
- VMBox挂载共享文件时可能出现的问题以及对应的解决办法
- MFC 资源脚本问题:fatal error CVT1100: 资源重复。类型: AFX DIALOG LAYOUT
- 解決Android嵌入百度地圖出現黑屏現象
- xml
- segue的几种模式