Chinaunix首页 | 论坛 | 博客
  • 博客访问: 262658
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-03-22 16:53:33



//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.
import java.util.HashSet;


public class LongestConsecutive {


public static void main(String[] args) {
// TODO 自动生成的方法存根

}
public static int longestConsecutive(int[] num) {
if(num.length==0){
return 0;
}
int max=1;
HashSet set=new HashSet();
for(int e:num){
set.add(e);
}
 
for(int e:num){


int left=e - 1;
int right=e + 1;
int count=1;
while(set.contains(left)){
count++;
set.remove(left);
left--;
}
while(set.contains(right)){
count++;
set.remove(right);
right++;

}
max=Math.max(max, count);
}
return max;
}


}
阅读(242) | 评论(0) | 转发(0) |
0

上一篇:LevelOrderTraversal

下一篇:Match

给主人留下些什么吧!~~