Problem 128: Longest Consecutive Sequence
思路
复杂度
public class Solution {
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer num : nums) {
if (map.containsKey(num)) continue;
int left = (map.containsKey(num - 1) ? map.get(num - 1) : 0);
int right = (map.containsKey(num + 1) ? map.get(num + 1) : 0);
int count = left + right + 1;
max = Math.max(max, count);
map.put(num, count);
if (left > 0) {
map.put(num - left, count);
}
if (right > 0) {
map.put(num + right, count);
}
}
return max;
}
}Last updated