问题描述:
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表,先初始化一个hash表, 存储所有数组元素, 然后遍历这个数组, 对找到的数组元素, 去搜索其相连的上下两个元素是否在hash表中, 如果在, 删除相应元素并增加此次查找的数据长度, 如果不在, 从下一个元素出发查找。
package suda.alex.leetcode;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class LongestConsecutive {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("input the size of num:");
int len = scanner.nextInt();
System.out.println("input num:");
int[] num = new int[len];
for (int i = 0; i < len; i++) {
num[i] = scanner.nextInt();
}
System.out.println("the longestConsecutive num is:"
+ longestConsecutive2(num));
}
public static int longestConsecutive1(int[] num) {
int len = num.length;
if (len == 0) {
return 0;
}
Arrays.sort(num);
int count = 1;
int maxLen = 1;
for (int i = 1; i < len; i++) {
if (num[i] == num[i - 1] + 1) {
count++;
} else {
if (num[i] != num[i - 1]) {
count = 1;
}
}
if (count > maxLen) {
maxLen = count;
}
}
return maxLen;
}
public static int longestConsecutive2(int[] num) {
int len = num.length;
if (len == 0) {
return 0;
}
Set<Integer> set = new HashSet<Integer>();
int maxLen = 1;
for (int i = 0; i < len; i++) {
set.add(num[i]);
}
for (int i = 0; i < len; i++) {
int count = 1;
int leftNum = num[i] - 1;
int rightNum = num[i] + 1;
while (set.contains(leftNum)) {
count++;
set.remove(leftNum);
leftNum--;
}
while (set.contains(rightNum)) {
count++;
set.remove(rightNum);
rightNum++;
}
if(count > maxLen){
maxLen = count;
}
}
return maxLen;
}
}