码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Consecutive Sequence

时间:2016-07-05 06:23:14      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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

Clarification

Your algorithm should run in O(n) complexity.

Example

Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

分析:

既然要求O(n) complexity,排序这种方法就放弃了。这里用了HashSet来保存每个数,然后从这个数开始,左右寻找是否有相邻的数。非常有新意的方法。

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers
 4      * @return an integer
 5      */
 6     public int longestConsecutive(int[] num) {
 7         if(num == null||num.length == 0) return 0;
 8         
 9         HashSet<Integer> hs = new HashSet<Integer>();  
10         
11         for (int i = 0 ;i < num.length; i++) {   
12             hs.add(num[i]);  
13         }
14          
15         int max = 0;  
16         for(int i = 0; i < num.length; i++){  
17             if(hs.contains(num[i])){
18                 int count = 1;  
19                 hs.remove(num[i]);
20                 
21                 int low = num[i] - 1; 
22                 while(hs.contains(low)){  
23                     hs.remove(low);  
24                     low--;  
25                     count++;  
26                 }
27                 
28                 int high = num[i] + 1;  
29                 while(hs.contains(high)){  
30                     hs.remove(high);  
31                     high++;  
32                     count++;  
33                 }  
34                 max = Math.max(max, count);  
35             }  
36         }  
37         return max;  
38     }
39 }

参考请注明出处:cnblogs.com/beiyeqingteng/

Longest Consecutive Sequence

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5642196.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!