【題目】*128. 最長連續序列
給定一個未排序的整數數組,找出最長連續序列的長度。
要求算法的時間複雜度爲 O(n)。
示例:
輸入: [100, 4, 200, 1, 3, 2]
輸出: 4
解釋: 最長連續序列是 [1, 2, 3, 4]。它的長度爲 4。
【解題思路1】哈希表
是否存在 num-1 作爲開始查找序列是否存在的判斷條件,也就是保證至少有兩個連續的序列,纔開始查找
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}
int longestStreak = 0;
for (int num : num_set) {
if (!num_set.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (num_set.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
}
對每一個num查找比他小的,再查找比他大的數字,查找到的連續序列內的數字從哈希表裏刪除,避免重複查找
class Solution {
public int longestConsecutive(int[] nums) {
HashSet<Integer> hash = new HashSet<>();
for(int i = 0; i < nums.length; i++){
hash.add(nums[i]);
}
int cnt = 0;
int result = 0;
int tmp1 = 0;
int tmp2 = 0;
for(int j = 0; j < nums.length; j++){
if(!hash.contains(nums[j])) continue;
cnt = 0;
tmp1 = nums[j];
tmp2 = nums[j]+1;
while(hash.contains(tmp1)) {
cnt++;
hash.remove(tmp1);
tmp1--;
}
while(hash.contains(tmp2)) {
cnt++;
hash.remove(tmp1);
tmp2++;
}
result = cnt > result ? cnt : result;
}
return result;
}
}