[LintCode]Longest Consecutive Sequence
Version 1 暴力方法 时间复杂度高
public class Solution {
/**
* @param nums: A list of integers
* @return an integer
*/
public int longestConsecutive(int[] num) {
// 2015-09-03 暴力方法 O(nlogn)
// num可能含重复元素
if (num == null || num.length == 0) {
return -1;
}
Arrays.sort(num); // O(nlogn)
// 去掉重复元素
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < num.length; i++) {
if (i != 0 && num[i - 1] == num[i]) {
continue;
}
list.add(num[i]);
}
int max = 0;
for (int i = 0; i < list.size(); i++) {
if (i != 0 && list.get(i) == list.get(i - 1) + 1) {
continue;
}
int sum = 1;
int index = i - 1;
int val = list.get(i);
while (index >= 0 && list.get(index) == val - 1) {
sum++;
index--;
val--;
}
index = i + 1;
val = list.get(i);
while (index < list.size() && list.get(index) == val + 1) {
sum++;
index++;
val++;
}
max = max < sum ? sum : max;
}
return max;
}
}
Version 2 用HashMap降低时间复杂度
public class Solution {
/**
* @param nums: A list of integers
* @return an integer
*/
public int longestConsecutive(int[] num) {
// write you code here
// HashMap: space O(n), time O(n)
// 用hashmap降低时间复杂度
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i: num) {
map.put(i, 0);
}
int rst = 1;
// 遍历 用hashmap做记录,已经遍历的为1,没有遍历的为0
for(int key: num) {
if (map.get(key) == 1) continue;
int max = 1;
int tmp = key;
while(map.containsKey(tmp+1)) {
max++;
tmp++;
map.put(tmp, 1);// 1是一个标志,表示这个点已经被算过了
}
tmp = key;
while(map.containsKey(tmp-1)) {
max++;
tmp--;
map.put(tmp, 1);
}
map.put(key, 1);
rst = Math.max(max, rst);
}
return rst;
}
}