Longest Consecutive Sequence
2015-08-04 11:10
423 查看
问题描述
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
Your algorithm should run in O(n) complexity.
解决思路
1. HashMap存储元素和对应的边界长度;
2. 插入元素n时,检查n-1和n+1是否在map中,如果在,则更新边界的长度,最后输出最大长度即可。
程序
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is
[1, 2, 3, 4]. Return its length:
4.
Your algorithm should run in O(n) complexity.
解决思路
1. HashMap存储元素和对应的边界长度;
2. 插入元素n时,检查n-1和n+1是否在map中,如果在,则更新边界的长度,最后输出最大长度即可。
程序
public class Solution { public int longestConsecutive(int[] nums) { if (nums == null || nums.length == 0) { return 0; } HashMap<Integer, Integer> map = new HashMap<>(); int max = 1; for (int n : nums) { if (map.containsKey(n)) { continue; } map.put(n, 1); if (map.containsKey(n - 1)) { max = Math.max(max, updateLen(map, n - 1, n)); } if (map.containsKey(n + 1)) { max = Math.max(max, updateLen(map, n, n + 1)); } } return max; } private int updateLen(HashMap<Integer, Integer> map, int a, int b) { int lower = a - map.get(a) + 1; int higher = b + map.get(b) - 1; int len = higher - lower + 1; map.put(lower, len); // update bound map.put(higher, len); return len; } }
相关文章推荐
- iOS-UIkit复习和代理的使用实现文本框限制输入字数控制
- no value specified for 'date' 的解决方法
- 队列 Queue 用链表实现队列
- 南邮 OJ 1088 Gnome Sequencing
- UIDatePicker 日期/时间选取器(滚轮)—IOS开发
- 1000多块整个插板,arduino + android 蓝牙插板的实现--屌丝版
- UI-ScrollView的使用
- String、StringBuffer和StringBuilder
- BluetoothAdapter.LeScanCallback 参考文档
- iOS多线程之NSOperation,NSOperationQueue
- PHP中 include,include_once,require,require_once的区别详解
- poj 3907 Build Your Home(任意多边形面积)
- ${pageContext.request.contextPath} JSP取得绝对路径
- Storyboard里面的几种Segue区别:push,modal,popover,replace和custom
- Android GUI之View测量
- Xamarin.Forms之FluentValidation(Model验证)
- easyui tabs update 强制刷新页面
- Android GUI之View测量
- NGUI Sprite Type类型详解
- js中获取 <%=request.getContextPath()%>