题目
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.
思路
1 因为只能O(n) 的时间来做,所以考虑时间转空间,用set来存储数据
2 重新遍历数组,当前元素为cur,然后找set中和它连续的值,计算总的长度,与max比较大小;同时set中找到的都要删除,这样为后续遍历到数组的元素就不会重复计算了。
代码
public class Solution {
public int longestConsecutive(int[] num) {
if(num.length ==0){
return 0;
}
HashSet<Integer> record = new HashSet<Integer>();
for(int i=0;i<num.length;i++){
record.add(num[i]);
}
int ans=0;
for(int i=0;i<num.length;i++){
int cur = num[i];
int temp =0;
if(record.contains(cur)){
record.remove(cur);
temp++;
while(record.contains(cur+1)){
record.remove(cur+1);
temp++;
cur++;
}
cur = num[i];
while(record.contains(cur-1)){
record.remove(cur-1);
temp++;
cur--;
}
ans = Math.max(temp,ans);
}
}
return ans;
}
}
public class Solution {
public int longestConsecutive(int[] num) {
if(num.length ==0){
return 0;
}
SortedSet<Integer> record = new TreeSet<Integer>();
for(int i=0;i<num.length;i++){
record.add(num[i]);
}
int ans = 1;
int pre = Integer.MAX_VALUE;
int temp =1;
for(Integer i:record){
if(i==pre+1){
temp++;
}
else{
ans = Math.max(ans,temp);
pre = i;
temp =1;
}
}
return ans;
}
}
public class Solution {
public int longestConsecutive(int[] num) {
Map<Integer,Integer> record = new HashMap<Integer,Integer>();
int ans =0;
for(int i=0;i<num.length;i++){
if(record.containsKey(num[i])){
continue;
}
int low = num[i];
int high = num[i];
if(record.containsKey(num[i]-1)){
low = record.get(num[i]-1);
}
if(record.containsKey(num[i]+1)){
high = record.get(num[i]+1);
}
ans = Math.max(ans,high-low+1);
record.put(num[i],num[i]);
record.put(low,high);
record.put(high,low);
}
return ans;
}
}
真正的O(n),考虑在record中的计数含义,如果它是最低点,记录最高点;如果它是中间点无所谓;如果它是最高点,记录最低点;如果它的单独点,就代表它自己。