[leetcode] Longest Consecutive Sequence
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.
https://oj.leetcode.com/problems/longest-consecutive-sequence/
思路:用hashset存储所有元素,对在hashset中某一元素,在hashset中删除,然后向前向后依次寻找还在hashset中的元素并删除,期间更新最大值。
public class Solution { public int longestConsecutive(int[] num) { if (num == null || num.length == 0) return 0; if (num.length == 1) return 1; HashSet<Integer> set = new HashSet<Integer>(); for (int each : num) set.add(each); int res = 0; for (int i = 0; i < num.length; i++) { int count = 0; if (set.contains(num[i])) { count++; set.remove(num[i]); int pre = num[i] - 1; while (set.contains(pre)) { set.remove(pre); count++; pre--; } int post = num[i] + 1; while (set.contains(post)) { set.remove(post); count++; post++; } } if (count > res) res = count; } return res; } public static void main(String[] args) { System.out.println(new Solution().longestConsecutive(new int[] { 1,2,4,5,6 })); } }
第二遍记录:
注意遍历的时候,是遍历num不是set,因为num可能有重复元素,size可能会小很多。
public class Solution { public int longestConsecutive(int[] num) { if(num==null||num.length==0) return 0; HashSet<Integer> set = new HashSet<Integer>(); for(int i=0;i<num.length;i++) set.add(num[i]); int res =1; for(int i=0;i<num.length;i++){ int count = 0; if(set.contains(num[i])){ count++; set.remove(num[i]); int pre = num[i]-1; while(set.contains(pre)){ count++; set.remove(pre); pre--; } int post =num[i]+1; while(set.contains(post)){ count++; set.remove(post); post++; } res=Math.max(res,count); } } return res; } }
参考:
http://blog.csdn.net/fightforyourdream/article/details/15024861