您的位置:首页 > 产品设计 > UI/UE

Longest Consecutive Sequence

2015-08-04 11:10 423 查看
问题描述

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. HashMap存储元素和对应的边界长度;

2. 插入元素n时,检查n-1和n+1是否在map中,如果在,则更新边界的长度,最后输出最大长度即可。

程序

public class Solution {
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}

HashMap<Integer, Integer> map = new HashMap<>();
int max = 1;

for (int n : nums) {
if (map.containsKey(n)) {
continue;
}
map.put(n, 1);
if (map.containsKey(n - 1)) {
max = Math.max(max, updateLen(map, n - 1, n));
}
if (map.containsKey(n + 1)) {
max = Math.max(max, updateLen(map, n, n + 1));
}
}

return max;
}

private int updateLen(HashMap<Integer, Integer> map, int a, int b) {
int lower = a - map.get(a) + 1;
int higher = b + map.get(b) - 1;
int len = higher - lower + 1;
map.put(lower, len); // update bound
map.put(higher, len);
return len;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: