问题描述:
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
解答:线性时间,空间为常数(该数组中最大元素的值)
算法:
1: public int[] longestConsecutiveSequence(int[] a)
2: {
3: int first = Integer.MAX_VALUE; // the first number of the maximum consecutive sequence
4: int length = 0; // the length of the maximum consecutive sequence
5: Map<Integer, Integer> table = new HashMap<Integer, Integer>();
6: for(int i: a) {
7: if(!table.containsKey(i)) {
8: int start = i;
9: int end = i;
10: if(table.containsKey(i + 1) && table.get(i + 1) >= i + 1) {
11: end = table.get(i + 1);
12: table.remove(i + 1);
13: table.remove(end);
14: }
15: if(table.containsKey(i - 1) && table.get(i - 1) <= i - 1) {
16: start = table.get(i - 1);
17: table.remove(i - 1);
18: table.remove(start);
19: }
20: table.put(start, end);
21: table.put(end, start);
22: if(end - start + 1 > length) {
23: first = start;
24: length = end - start + 1;
25: }
26: }
27: }
28: System.out.println(table);
29: System.out.println(length);
30: int[] s = new int[length];
31: for(int i = 0; i < length; i++) s[i] = first + i;
32: return s;
33: }