标签:
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)
1 public class Solution { 2 public int longestConsecutive(int[] nums) { 3 if(nums.length==1){ 4 return 1; 5 } 6 Set<Integer> arrset = new HashSet<Integer>(); 7 for(int i=0;i<nums.length;i++){ 8 arrset.add(nums[i]); 9 } 10 Iterator<Integer> iter = arrset.iterator(); 11 int max = 0; 12 while(iter.hasNext()){ 13 int count1=0; 14 int count2=0; 15 int a = iter.next()+1; 16 int b = a-2; 17 iter.remove(); 18 Iterator<Integer> it1 = arrset.iterator(); 19 if(it1.hasNext()){ 20 while(it1.hasNext() && arrset.contains(a++)){ 21 count1++; 22 arrset.remove(a-1); 23 } 24 } 25 Iterator<Integer> it2 = arrset.iterator(); 26 if(it2.hasNext()){ 27 while(it2.hasNext()&& arrset.contains(b--)){ 28 count2++; 29 arrset.remove(b+1); 30 } 31 } 32 max = Math.max(max,count1+count2+1); 33 iter = arrset.iterator(); 34 } 35 return max; 36 } 37 }
[Leetcode]Longest Consecutive Sequence
标签:
原文地址:http://www.cnblogs.com/jamweak/p/4655865.html