您的位置:首页 > 其它

求数组中包含的最长子序列

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


解答:线性时间,空间为常数(该数组中最大元素的值)

算法:

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: