原题链接在这里:https://leetcode.com/problems/longest-consecutive-sequence/
当成树来看,看最长的一支有多少点。
借用HashSet数据结构,先把所有点放入hs中,从nums[0]开始检查是否包含这个点,若是包含,就看它往下能走多远,然后看往上能走多远,走过的点从hs中移除,更新最大值。
Time Complexity O(n), Space O(n).
AC Java:
1 public class Solution { 2 public int longestConsecutive(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return 0; 5 } 6 HashSet<Integer> hs = new HashSet<Integer>(); 7 //put every element into hashset 8 for(int i = 0; i<nums.length; i++){ 9 hs.add(nums[i]); 10 } 11 int res = 0; 12 for(int i = 0; i<nums.length; i++){ 13 if(hs.contains(nums[i])){ 14 int count = 1; 15 //check how many nodes are there in lower branch 16 int low = nums[i] - 1; 17 while(hs.contains(low)){ 18 hs.remove(low); 19 low--; 20 count++; 21 } 22 //check how many nodes are there in higher branch 23 int high = nums[i] + 1; 24 while(hs.contains(high)){ 25 hs.remove(high); 26 high++; 27 count++; 28 } 29 res = Math.max(res,count); 30 } 31 } 32 return res; 33 } 34 }
LeetCode Longest Consecutive Sequence
原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4888868.html