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

Longest Consecutive Sequence

2016-01-20 16:00 447 查看
题目:

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(nlogn),将大于O(n)。所以此题不能排序,那么久得想另外的方法。在网上提供了一种非常好的方法,就是采用一个Set来保存数组中的数字,因为从此题的题意来看,这个数组应该是没有重复元素出现,所以我们可以看到,先将所有元素都加入到这个Set中去,然后就是利用我们可以从第一个数字开始,向它的两边查看有没有连续的元素在Set中,如果有,那么将连续的长度加1,然后将那个连续的元素从Set中删除;至于这里可能会有疑惑,就是关于为什么要将这个元素删除,有没有可能会导致在下一个连续的元素出现的时候,将这个元素删除了,然后就少了呢?但是细想是不会的,因为我们可以想到,如果下一个有可能会出现更大的连续数,也必定不会在刚才的这个连续序列中,而必定是另外开的一个序列,所以不用担心这个问题。那么我们可以直接在首次循环的时候直接将这个数字删除。

public class Solution
{
public int longestConsecutive(int[] nums)
{
if(nums == null || nums.length == 0)
return 0;
int max = 1;
Set<Integer> set = new HashSet<Integer>();
for(int i : nums)
set.add(i);
for(int j : nums)
{
int left = j - 1;
int right = j + 1;
int count = 1;
while(set.contains(left))
{
count++;
set.remove(left);
left--;
}
while(set.contains(right))
{
count++;
set.remove(right);
right++;
}
max = Math.max(max,count); //这个count是每次都在变的,每次一个连续的循环完之后,就和max对比
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: