/**
* 求随机数构成的数组中找到长度大于=3的最长的等差数列
* 输出等差数列由小到大: 如果没有符合条件的就输出[0,0]
* 格式:
* 输入[1,3,0,5,-1,6]
* 输出[-1,1,3,5]
* 要求时间复杂度,空间复杂度尽量小
*
*
* 动态规划 二次哈希
*
* 时间复杂度为O(n*n)
*
*
*/
public class SameSubSeqence {
public static int find(int[] a) throws Exception {
assert (true);
int max = 0;
QuickSort.quickSort(a, 0, a.length - 1);
HashMap<Integer, HashMap<Integer, Integer>> map = new HashMap<Integer, HashMap<Integer, Integer>>();
for (int i = 0; i < a.length; i++) {
int thisMax = 1;
HashMap<Integer, Integer> myMap = map.get(a[i]);
if (myMap != null) {// 可能有相同 的元素,构成等差为0的序列。
Integer v = myMap.get(0);
myMap.put(0, v.intValue() + 1);
continue;
} else {
myMap = new HashMap<Integer, Integer>();
map.put(a[i], myMap);
myMap.put(0, 1);// 表示等差为0的序列的起始。
}
for (int j = 0; j < i; j++) {// 挨个与前面的元素比较
HashMap<Integer, Integer> hisMap = map.get(a[j]);
int key = a[i] - a[j];
Integer v = hisMap.get(key);
if (v != null) {
myMap.put(key, v.intValue() + 1);
} else {
myMap.put(key, 2);
}
// 获取当前最大值。
if (myMap.get(key) > thisMax) {
thisMax = myMap.get(key);
}
}
if (thisMax > max) {
max = thisMax;
}
}
return max;
}
/**
* @param args
*/
public static void main(String[] args) {
int[] a = { 1, 3, 0, 9, 5, -1, 6, 7 };
try {
int max = SameSubSeqence.find(a);
System.out.println(max);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最长等差子序列
最新推荐文章于 2023-04-27 22:25:06 发布