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

【Leetcode】Longest Consecutive Sequence

2016-06-10 20:21 351 查看
题目链接:https://leetcode.com/problems/longest-consecutive-sequence/

题目:

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、-1是否在数组中,如果遍历数组来查找显然时间复杂度要大于O(n),考虑用HashSet可以方便的知道一个元素是否在集合中,如果一个元素+1/-1都不在集合中,则删去该元素,并且每一个元素判断后都删除,则时间复杂度为O(n)。

算法:

[java] view
plain copy







public int longestConsecutive(int[] nums) {

int max = 1;

Set<Integer> set = new HashSet<Integer>();

for (int i = 0; i < nums.length; i++) {

set.add(nums[i]);

}

for (int i = 0; i < nums.length; i++) {

int length = 1; // 当前元素连续长度

if (set.contains(nums[i] + 1) || set.contains(nums[i] - 1)) {

int cur = nums[i];

while (set.contains(cur + 1)) {

length++;

set.remove(cur + 1);

cur++;

}

cur = nums[i];

while (set.contains(cur - 1)) {

length++;

set.remove(cur - 1);

cur--;

}

}

set.remove(nums[i]);

max = Math.max(length, max);

}

return max;

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