*LeetCode-Longest Consecutive Sequence
2015-10-07 04:28
501 查看
用了一个hashmap存每个数字到目前为止最长的length
没加入一个数 看他的n-1和n+1在不在map里面 假如在 那左边数字的value就是n左边有多少个连续数字 不存在左边长度就是0
右边同理 然后length = leftLen + rightLen + 1 放入
最重要的一步是要push boundary,自己更新之后 最左边和最右边的数字也要更新 以便以后使用
之中keep了一个max
public class Solution {
public int longestConsecutive(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
if ( nums == null || nums.length == 0 )
return 0;
int max = 0;
for ( int n : nums ){
if ( !map.containsKey( n )){
int leftLen = map.containsKey( n - 1) ? map.get( n - 1 ) : 0;
int rightLen = map.containsKey( n + 1 ) ? map.get ( n + 1 ) : 0;
int length = leftLen + rightLen + 1;
max = Math.max ( max, length );
map.put ( n, length );
map.put ( n - leftLen, length );
map.put ( n + rightLen, length );
}
}
return max;
}
}
没加入一个数 看他的n-1和n+1在不在map里面 假如在 那左边数字的value就是n左边有多少个连续数字 不存在左边长度就是0
右边同理 然后length = leftLen + rightLen + 1 放入
最重要的一步是要push boundary,自己更新之后 最左边和最右边的数字也要更新 以便以后使用
之中keep了一个max
public class Solution {
public int longestConsecutive(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
if ( nums == null || nums.length == 0 )
return 0;
int max = 0;
for ( int n : nums ){
if ( !map.containsKey( n )){
int leftLen = map.containsKey( n - 1) ? map.get( n - 1 ) : 0;
int rightLen = map.containsKey( n + 1 ) ? map.get ( n + 1 ) : 0;
int length = leftLen + rightLen + 1;
max = Math.max ( max, length );
map.put ( n, length );
map.put ( n - leftLen, length );
map.put ( n + rightLen, length );
}
}
return max;
}
}
相关文章推荐
- Failed to instantiate the default view controller for UIMainStoryboardFile 'Main'
- request方法大全
- 规律+DFS Codeforces Round div2 D. Equivalent Strings
- APUE CH7 Environ
- HDU 3157 Crazy Circuits
- 两道人数多,课程少,query多的题
- easyUI parser的使用
- easyUI 初始化的两种方式
- QueryBuildRange的各种条件的总结
- UINavigationBar自定义返回按钮
- UI 动画之CALayer+CAAnimation 之 CATransition
- HDU 4848 Wow! Such Conquering! 搜索+剪枝
- UI 动画之CALayer+CAAnimation 之 CAAnimationGroup
- UIKit学习笔记2
- UIKit学习笔记1
- UI 动画之CALayer+CAAnimation 之 CAKeyframeAnimation
- 设计模式之ChainOfResponsibility:过滤Request和Response
- UI_数据处理(model)
- Notepad++配合QuickText打造快速高效的文本编辑器
- UI 动画之CALayer+CAAnimation 之 CABasicAnimation