求数组中包含的最长子序列
2013-10-22 08:36
344 查看
问题描述:
Given an int array which might contain duplicates, find the largest subset of it which form a sequence.
Eg. {1,6,10,4,7,9,5}
then ans is 4,5,6,7
解答:线性时间,空间为常数(该数组中最大元素的值)
算法:
Given an int array which might contain duplicates, find the largest subset of it which form a sequence.
Eg. {1,6,10,4,7,9,5}
then ans is 4,5,6,7
解答:线性时间,空间为常数(该数组中最大元素的值)
算法:
public int[] longestConsecutiveSequence(int[] a)
{
int first = Integer.MAX_VALUE; // the first number of the maximum consecutive sequence
int length = 0; // the length of the maximum consecutive sequence
Map<Integer, Integer> table = new HashMap<Integer, Integer>();
for(int i: a) {
if(!table.containsKey(i)) {
int start = i;
int end = i;
if(table.containsKey(i + 1) && table.get(i + 1) >= i + 1) {
end = table.get(i + 1);
table.remove(i + 1);
table.remove(end);
}
if(table.containsKey(i - 1) && table.get(i - 1) <= i - 1) {
start = table.get(i - 1);
table.remove(i - 1);
table.remove(start);
}
table.put(start, end);
table.put(end, start);
if(end - start + 1 > length) {
first = start;
length = end - start + 1;
}
}
}
System.out.println(table);
System.out.println(length);
int[] s = new int[length];
for(int i = 0; i < length; i++) s[i] = first + i;
return s;
}
相关文章推荐
- 使用JAXP进行DOM解析( DocumentBuilderFactory、DocumentBuilder、Document)
- VC++中使用内存映射文件处理大文件(转)
- proc源码解析(一)--proc文件系统的内容
- xml
- BMP位图结构与操作(转)
- 深入剖析oracle一致性读
- 有感李清照离婚
- baidu推送消息定制开发
- android Intent
- 查看所有端口占用
- Centos 系统,如果忘记了root用户密码
- MFC教程-应用程序的退出
- 2013年国内IT 行业薪资情况
- 黑马程序员——java基础加强
- SASS详解之基本语法
- winsock阻塞模式下错误代码10014
- UVa 10785 The Mad Numerologist (排序)
- 约瑟夫环(链表实现)
- 24个春秋·理想·爱情·祭
- 32位与64位操作系统区别