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.
題目大意:給一個無序陣列,找出最大的連續元素的長度。
說真的,一開始這題,我想半天只想到用boolean陣列mark,後來看了別人的才發現可以用set做。
解題思路:
把所有的陣列放到set中,然後遍歷陣列的元素,然後分別向前、向後尋找set中是否存在,記錄max。
public int longestConsecutive(int[] nums) {
if(nums==null||nums.length==0){
return 0;
}
Set<Integer> set = new HashSet<>();
for(int num:nums){
set.add(num);
}
int max = 0;
for(int i=0;i<nums.length;i++){
Integer num = nums[i];
int cnt = 1;
while(set.contains(--num)){
cnt++;
set.remove(num);
}
num=nums[i];
while(set.contains(++num)){
cnt++;
set.remove(num);
}
max=Math.max(max,cnt);
}
return max;
}