給定一個未排序的整數數組,找出最長連續序列的長度。
要求算法的時間複雜度爲 O(n)。
輸入: [100, 4, 200, 1, 3, 2]
輸出: 4
解釋: 最長連續序列是 [1, 2, 3, 4]。它的長度爲 4。
1、排序 : O(nlgn)
public int longestConsecutive(int[] nums) {
//排序
Arrays.sort(nums);
//最終結果(最長序列)
int max = 1;
//當前連續序列長度
int result = 1;
for(int i = 1,len =nums.length; i < len; i++){
if(nums[i] == nums[i-1] + 1){
result += 1;
}else{
//判斷序列長度大小
max = Math.max(result, max);
result = 1;
}
}
return Math.max(result, max);
}
2、Hash: O(n)
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet();
for(int i = 0,len = nums.length; i < len; i++){
set.add(nums[i]);
}
int max = 1;
int result;
for(Integer integer : set){
result = 1;
if(set.contains(integer-1)){
int currentNum = integer;
while(set.contains(currentNum++)){
result ++;
}
max = Math.max(result, max);
}
}
return max;
}