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.
思路:要找最长连续子串,首先一定数组中的每个元素都走一趟了,才能确定‘最长’子串。其次,有一个复杂度的要求O(N),也就是数组最多只能遍历一次。这里通过Hashmap,它可以记录哪些数据访问过,如果这个元素没有访问过,同时与上一个元素连续(递增/递减),则定位到当前元素,长度+1. 就这样连续走一趟就得到结果了。
public class Solution {
public int longestConsecutive(int[] num) {
HashMap<Integer, Boolean> hm = new HashMap<>();
for (int i = 0; i < num.length; i++) {
hm.put(num[i], false);
}
int longest = 0, high,low;
for(int i=0; i<num.length; i++){
if(hm.get(num[i]))
continue;
int len=1;
hm.put(num[i], true);
high=num[i]+1;
while(hm.containsKey(high)){
hm.put(high, true);
len++;
high++;
}
low=num[i]-1;
while(hm.containsKey(low)){
hm.put(low, true);
len++;
low--;
}
longest = Math.max(longest, len);
}
return longest;
}
}