首页 > 其他 > 详细

LeetCode: Longest Consecutive Sequence

时间:2014-03-11 11:41:04      阅读:524      评论:0      收藏:0      [点我收藏+]

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

 

这个题想了半天,没有想到合适的方法。如何能不排序,还能找到连续子序列呢。。。

后来看网上写的,就知道怎么做了。

用hash表,将每个元素保存下来。然后判断每个元素的左右两侧,是否有连续的序列。

需要注意的是,为了避免重复检查,需要把每次处理过的元素删除。

bubuko.com,布布扣
 1 public class Solution {
 2     public int longestConsecutive(int[] num) {
 3         HashSet<Integer> set = new HashSet<Integer>();
 4         for (int i : num) set.add(i);
 5         
 6         int maxlen = 0;
 7         for (int i : num) {
 8             int len = 1;
 9             if (set.contains(i)) {
10                 int j = i - 1;
11                 while (set.contains(j)) {
12                     set.remove(j--);
13                     len++;
14                 }
15                 j = i + 1;
16                 while (set.contains(j)) {
17                     set.remove(j++);
18                     len++;
19                 }
20             }
21             if (len > maxlen) {
22                 maxlen = len;
23             }
24         }
25         
26         return maxlen;
27     }
28 }
bubuko.com,布布扣

LeetCode: Longest Consecutive Sequence,布布扣,bubuko.com

LeetCode: Longest Consecutive Sequence

原文:http://www.cnblogs.com/longhorn/p/3589862.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!