Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
解釋下題目:
找出數組中的最長序列的長度
1. 類似動態規劃的思想
實際耗時:8ms
public int longestConsecutive(int[] nums) {
int res = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
continue;
}
int left = 0, right = 0;
if (map.containsKey(num - 1)) {
left = map.get(num - 1);
}
if (map.containsKey(num + 1)) {
right = map.get(num + 1);
}
int tmp = left + right + 1;
map.put(num, tmp);
map.put(num - left, tmp);
map.put(num + right, tmp);
res = Math.max(res, tmp);
}
return res;
}
??題目中要求時間復雜度是O(n),所以排序是斷斷不可能了的。也就是按序遍歷下去,就能知道最大的解,那么就需要類似動態規劃的結構,記錄下每個數字的最大的答案,然后后面的數字出現了再去更新前面數字的解即可,所以想到用map這個數據結構。其實也不復雜,每當一個數字進來的時候,比如是5吧,我們就找比它小一的數字4和比它大一的數字6中記錄的值,這兩個值記錄的是以4和6為邊界的數組的長度,如果沒有就是0。然后就能計算出這個數字5目前最大的邊界,然后同時更新一下4和6的邊界,最后在更新一下最大邊界的值就可以了。