47.创新工场:求最长递减子序列

求一个数组的最长递减子序列比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}


HANDWRITING:

int sequence(int *input, int size, int *output) {
	int *len = new int[size];
	int max = 1, pos = 0;
	len[0] = 1;
	for (int i = 1; i < size; ++i) {
		if (input[i] < input[i - 1]) {
			len[i] = len[i - 1] + 1;
			if (len[i] > max) max = len[i], pos = i;
		}
		else len[i] = 1;
	} 
	pos -= max - 1;
	for (int i = 0; i < max; ++i) {
		output[i] = input[pos + i];
	}
	delete [] len;
	return max;
}


ANSWER
FROM:http://blog.csdn.net/v_july_v/article/details/6870251

Scan from left to right, maintain a decreasing sequence. For each number, binary search in the decreasing sequence to see whether it can be substituted.

int[] findDecreasing(int[] a) {
  int[] ds = new int[a.length];
  Arrays.fill(ds, 0);
  int dsl = 0;
  int lastdsl = 0;
  for (int i=0; i<a.length; i++) {
    // binary search in ds to find the first element ds[j] smaller than a[i]. set ds[j] = a[i], or append a[i] at the end of ds
    int s=0, t=dsl-1;
    while (s<=t) {
      int m = s+(t-s)/2;
      if (ds[m] < a[i]) {
        t = m - 1;
      } else {
        s = m + 1;
      }
    }
    // now s must be at the first ds[j]<a[i], or at the end of ds[]
    ds[s] = a[i];
    if (s > dsl) { dsl = s; lastdsl = i; }
  }
  // now trace back.
  for (int i=lastdsl-1, j=dsl-1; i>=0 && j >= 0; i--) {
    if (a[i] == ds[j]) { j --; }
    else if (a[i] < ds[j]) { ds[j--] = a[i]; }
  }  
  return Arrays.copyOfRange(ds, 0, dsl+1);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值