最长等差子序列

/**
 * 求随机数构成的数组中找到长度大于=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();
		}

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值