【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
The longest consecutive elements sequence is
Your algorithm should run in O(n) complexity.
思路:
因为要不断地确认 一个数的+1、-1是否在数组中,如果遍历数组来查找显然时间复杂度要大于O(n),考虑用HashSet可以方便的知道一个元素是否在集合中,如果一个元素+1/-1都不在集合中,则删去该元素,并且每一个元素判断后都删除,则时间复杂度为O(n)。
算法:
[java] view
plain copy
![](https://code.csdn.net/assets/CODE_ico.png)
![](https://code.csdn.net/assets/ico_fork.svg)
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;
}
题目:
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
![](https://code.csdn.net/assets/CODE_ico.png)
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;
}
相关文章推荐
- UITableView性能优化 以及动态计算cell高度 新方法
- [LeetCode][9]Palindrome Number解析与StringBuilder.reverse()源码实现 -Java实现
- Building Roads_poj2749_2-sat+二分
- duilib第四天 2016年6月10日
- Ten Important Differences between Bluetooth BR/EDR and Bluetooth Smart
- iOS安全编码指南 Secure Coding Guide -- 02 Types of Security Vulnerabilities 上
- Codeforces645E Intellectual Inquiry
- java下简单GUI布局与监听
- 转发 源框架GPUImag
- 基于QtQuick2.0应用程序运行于XP系统的诸多问题
- iOS9 获取手机的唯一标识(一)——CFUUID、NSUUID、IDFA、IDFV、UDID、OpenUDID 的区别
- bzoj3339 rmq problem (range mex query)
- maven_创建quickstart模板时异常
- iOS小技巧20-iOS UILabel 文字设置垂直居中、垂直靠上、垂直靠下,设置edgeInsets
- Androidstuido编译加速
- IOS UITableView删除增加操作
- android - See Build Numbers for a full listing of branches you may choose from
- android - Establishing a Build Environment
- Servlet中的Response和Request
- MUI 按两次返回键退出应用 及 地理位置获取