LeetCode 128. Longest Consecutive Sequence
原题链接在这里:https://leetcode.com/problems/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.
题解:
用HashSet把所有点放入hs中.
在从头逐个检查是否包含这个点,若是包含,就看它往下能走多远,然后看往上能走多远,走过的点从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> set = new HashSet<Integer>(); 7 for(int num : nums){ 8 set.add(num); 9 } 10 11 int res = 0; 12 for(int num : nums){ 13 if(set.contains(num)){ 14 int count = 1; 15 set.remove(num); 16 17 //check how many nodes are there in lower branch 18 int low = num-1; 19 while(set.contains(low)){ 20 count++; 21 set.remove(low); 22 low--; 23 } 24 25 //check how many nodes are there in higher branch 26 int high = num+1; 27 while(set.contains(high)){ 28 count++; 29 set.remove(high); 30 high++; 31 } 32 33 res = Math.max(res, count); 34 } 35 } 36 return res; 37 } 38 }