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

[Leetcode]Longest Consecutive Sequence

2015-07-17 22:47 549 查看
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.

思路:

先用set存储数组中的不同元素。然后对Set内的元素进行顺序查找,过程如下:

1.读取集合中的头元素a,将其从集合中删除;

2.在集合中查找a+1的值是否存在(set.contains()方法),如果有则删除该元素,继续查找a+2...a+m,a+m+1不存在,则跳出循环;

3.在集合中查找a-1的值是否存在,如果有则元素,继续查找a-2...a-p,a-p-1不存在,则跳出循环;

4.记录m+p+1的值则是此次查找出的最长连续序列数,将其与max比较,选择最大的;

5.再次选择头元素,重复上述过程,直到集合元素遍历完。

代码:(Java)

public class Solution {
public int longestConsecutive(int[] nums) {
if(nums.length==1){
return 1;
}
Set<Integer> arrset = new HashSet<Integer>();
for(int i=0;i<nums.length;i++){
arrset.add(nums[i]);
}
Iterator<Integer> iter = arrset.iterator();
int max = 0;
while(iter.hasNext()){
int count1=0;
int count2=0;
int a = iter.next()+1;
int b = a-2;
iter.remove();
Iterator<Integer> it1 = arrset.iterator();
if(it1.hasNext()){
while(it1.hasNext() && arrset.contains(a++)){
count1++;
arrset.remove(a-1);
}
}
Iterator<Integer> it2 = arrset.iterator();
if(it2.hasNext()){
while(it2.hasNext()&& arrset.contains(b--)){
count2++;
arrset.remove(b+1);
}
}
max = Math.max(max,count1+count2+1);
iter = arrset.iterator();
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: