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.

思路

先对数组排序,然后用DP

 1 public class Solution {
 2     public int longestConsecutive(int[] num) {
 3         Arrays.sort(num);
 4         int curLength = 1;
 5         int maxLength = 1;
 6         
 7         for(int i = 1; i < num.length; i++){
 8             if(num[i] == num[i - 1])
 9                 continue;
10             else if(num[i] - num[i - 1] == 1){
11                 curLength ++;
12                 maxLength = maxLength > curLength ? maxLength : curLength;
13             }
14             else
15                 curLength = 1;
16         }//for
17         
18         return maxLength;
19     }
20 }

 上面思路时间复杂度为O(N*logN)

题目要求用O(n)这里可以借助hashtable或者hashmap,先将数组全部放到hash表中,在遍历数组,找到前面和后面的数,这里利用了hash通过get方法时间复杂度为o(1)

 1 import java.util.Hashtable;
 2 
 3 public class Solution {
 4     public int longestConsecutive(int[] num) {
 5         Hashtable<Integer, Integer> map = new Hashtable<Integer, Integer>();
 6         for(int i = 0; i < num.length; i++){
 7             map.put(num[i], 1);
 8         }//放到hash表中
 9         
10         int result = 0;
11         for(int i = 0; i < num.length; i++){
12             int sum = 1;
13             if(map.get(num[i]) != null){
14                 int left = num[i] - 1;
15                 map.remove(num[i]);
16                 while(map.get(left) != null){
17                     sum ++;
18                     map.remove(left);
19                     left--;
20                 }//while
21                 int right = num[i] + 1;
22                 while(map.get(right) != null){
23                     sum++;
24                     map.remove(right);
25                     right++;
26                 }//while
27                 
28                 result = result > sum ? result : sum;
29             }//if
30         }//for
31         
32         return result;
33     }
34 }
原文地址:https://www.cnblogs.com/luckygxf/p/4248340.html