Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
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/
原文:http://www.cnblogs.com/beiyeqingteng/p/5642196.html