描述
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.
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.
如果先排序然后再找出连续数字是一个简单的思路,但是复杂度不能满足O(n)。
下面是一种利用Hash表的方法,遍历每个元素,找到左右连续比它大或小的连续数字,假设数组长度为length,那么寻找比它大的连续最大数字也就是+length,比它小的连续的最小数字也就是-length。找过的数字则标示为true标示已经找过可以忽略。
package com.foo.leetcode.string;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LongestConsecutiveSequence {
public static int[] longestConsecutiveSequence(int[] data){
Map<Integer, Boolean> map = new HashMap<Integer,Boolean>();
List<Integer> result = new ArrayList<Integer>() ;
for(int a: data){
map.put(a, false);
System.out.print(a+" " );
}
System.out.println(" " );
int longest = 1;
for(int i=0; i<data.length ; i++){
List<Integer> tmp = new ArrayList<Integer>();
tmp.add(data[i]);
int length = 1;
if(!map.get(data[i]) ){
map.put(data[i], true);
for(int j = data[i]+1; j < data[i]+data.length; j++){
if(map.containsKey(j) ){
length ++;
tmp.add(j);
map.put(j, true);
}
else{
break;
}
}
for(int j = data[i]-1; j > data[i]-data.length; j--){
if(map.containsKey(j) ){
length ++;
tmp.add(j);
map.put(j, true);
}
else{
break;
}
}
}
if(longest > length){
}else{
longest = length;
System.out.println("longest:"+longest);
result.clear();
result.addAll( tmp);
}
}
int[] res = new int[longest];
for(int i=0; i<result.size(); i++){
res[i] = result.get(i);
}
return res;
}
public static void main(String[] args) {
System.out.println("test LongestConsecutiveSequence:");
int[] input = new int[]{5,4,56,3,12,2,1,12,11,13};
int[] result = longestConsecutiveSequence(input);
for(int i=0;i<result.length;i++)
System.out.println(result[i]);
}
}