LeetCode: Longest Consecutive Sequence

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

 

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

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

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

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

 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 }

 

posted on 2014-03-09 13:16  longhorn  阅读(168)  评论(0编辑  收藏  举报

导航