129.Longest Consecutive Sequence
2016-05-12 22:28
363 查看
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
Your algorithm should run in O(n) complexity.
Subscribe to see which companies asked this question
Step1:先把所有的元素都存入到set中;
Step2:遍历set中的元素,针对这个元素把所有连续比它大的元素都删除,然后再把所有比它小的元素都删除,并记录下个数;
Step3:继续遍历set中剩下的元素,重复Step2。
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.
Subscribe to see which companies asked this question
Step1:先把所有的元素都存入到set中;
Step2:遍历set中的元素,针对这个元素把所有连续比它大的元素都删除,然后再把所有比它小的元素都删除,并记录下个数;
Step3:继续遍历set中剩下的元素,重复Step2。
/** * 给定一个未排序的数组,求该数组中元素连续的最大长度。 * Given [100, 4, 200, 1, 3, 2], * The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. * 思路: * Step1:先把所有的元素都存入到set中; * Step2:遍历set中的元素,针对这个元素把所有连续比它大的元素都删除,然后再把所有比它小的元素都删除,并记录下个数; * Step3:继续遍历set中剩下的元素,重复Step2。 * @date 20160512 */ public int longestConsecutive(int[] nums) { int len = nums.length; if(len <= 0){ return 0; } int result = 1; Set<Integer> set = new HashSet<Integer>(len); for(int i=0;i<len;i++){ set.add(nums[i]); } Iterator<Integer> it = set.iterator(); while(!set.isEmpty()){ it = set.iterator(); int element = it.next(); set.remove(element); int next = element+1;//比element大的元素 int pre = element-1; while(set.contains(next)){ set.remove(next); next++; } while(set.contains(pre)){ set.remove(pre); pre--; } if(result < next-pre-1){ result = next-pre-1; } } return result; }
相关文章推荐
- iOS开发封装带有Button的UIView控件,使用代理给button添加点击事件
- deep learning---利用caffe在vgg-face上finetuing自己的人脸数据
- mui图片预览
- weblogic 下异常 org.hibernate.QueryException: ClassNotFoundException: org.hibernate.hql.ast.HqlToken
- 62. Unique Paths
- leetcode_347 Top K Frequent Elements
- Guid的使用
- iOS开发封装带有Button的UIView控件,使用block给button添加点击事件
- String StringBuffer与StringBuilder的区别
- Java 设计模式-建造者模式(Builder)Android讲解
- POJ 3061 - Subsequence
- StringBuilder的使用
- ugui 添加事件的几种方式
- Guid的使用
- StringBuilder的使用
- layer.layui.com 一个不错的弹窗层js插件库
- UIscrollView
- 1711 Number Sequence(kmp)
- Android的线程使用来更新UI------Thread Handler Looper TimerTask等
- 303. Range Sum Query - Immutable