最长递减子序列 【微软面试100题 第四十七题】
来源:互联网 发布:大学软件开发专业 编辑:程序博客网 时间:2024/05/22 02:15
题目要求:
求一个数组的最长递减子序列;
比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}。
代码实现:
代码1:动态规划,时间复杂度O(N^2).
#include <iostream>using namespace std;const int N = 8;int Lis(int a[],int n);int main(void){ int a[] = {1,-1,2,1,4,-5,6,-7}; cout << Lis(a,N) << endl; return 0;}int Lis(int a[],int n){ int *B = new int[n]; int i,j,max; for(i = 0;i<n;i++) { B[i] = 1; for(j = 0;j<i;j++) { if(a[i]<a[j] && B[j]+1>B[i]) B[i] = B[j]+1; } } max = B[0]; for(i = 1;i<n;i++) { if(max<B[i]) max = B[i]; } return max;}
代码2:使用二分搜索提速,时间复杂度O(N*logN).
#include <iostream>using namespace std;const int N = 8;int Lis(int a[],int n);int main(void){ int a[] = {1,-1,2,1,4,-5,6,-7}; cout << Lis(a,N) << endl; return 0;}int Lis(int a[],int n){ int *B = new int[n]; int i,left,right,mid,len = 1; B[0] = INT_MAX; B[1] = a[0]; for(i = 1;i<n;i++) { left = 0; right = len; while(left<=right) { mid = (left+right)/2; if(B[mid]>a[i]) left = mid+1; else right = mid-1; } B[left] = a[i]; if(left>len) len++; } return len;}
0 0
- 最长递减子序列 【微软面试100题 第四十七题】
- 第四十七题(求最长递减子序列)
- 微软100题(47)最长递减子序列
- 【100题】 第四十七题 序列的最长递增、递减序列
- 最长递减子序列
- 最长递减子序列
- 最长递减子序列
- 最长递减子序列
- 最长递减子序列
- 微软算法经典3 求最长递减子序列
- 最长公共子序列 【微软面试100题 第五十六题】
- 最长公共子序列 【微软面试100题 第五十六题】
- 第四题 最长公共子序列
- pku1887 最长递减子序列
- 最长单调递减子序列
- poj1887(最长递减子序列)
- 最长递减子序列[转载]
- 最长递增/递减子序列
- Local database deployment problems and fixtures
- Chromium Graphics Update in 2014(幻灯片)
- Sicily 1029. Rabbit【高精度加法】
- Hibernate 表关系描述之ManyToMany
- Hive编程指南学习笔记(1)
- 最长递减子序列 【微软面试100题 第四十七题】
- Android Launcher3源码分析与修改
- Get和Post的区别
- JAVA——jdk安装
- #pragma once 与 #ifndef 解析
- Android 使用主题资源
- C++的特性
- Clickjacking简单介绍
- 判断点在多边形内的算法