编程之美2.16最长递增子序列
来源:互联网 发布:清茶淘宝助手充值卡 编辑:程序博客网 时间:2024/06/05 06:33
思想:
对每一个长度建立其最大值的记录maxV,当输入一个新值v时,找到最大值小于v的最后一个索引i,若i为maxV的最后一个索引,则最大长度maxL+1,否则maxV[i+1]=v;
代码:
#include <iostream>#include <vector>#include <string>#include <cmath>#include <sstream>#include <bitset>using namespace std;int find_index(vector<int> vec,int v) //找到最后一个<=v的索引{int l=0,r=vec.size()-1;while (l<r){int mid = (l+r+1)/2;if (vec[mid]<v){l = mid;}else{r = mid-1;}}if (l==r&&vec[l]<v) return l;return -1;}int longestIncrementSequence(vector<int> &seq){if (seq.size()==0) return 0;vector<int> maxV;int maxL = 1;maxV.push_back(seq[0]);int index;for (int i=1;i<seq.size();++i){index = find_index(maxV,seq[i]);if (index!=-1){if (index==maxV.size()-1){maxL++;maxV.push_back(seq[i]);}else{maxV[index+1] = seq[i];}}if (maxV.size()==1&&maxV[0]>seq[i]){maxV[0] = seq[i];}}return maxL;}int main(){vector<int> v;int n;while (cin>>n){while (n--){int m;cin>>m;v.push_back(m);}cout<<longestIncrementSequence(v)<<endl;}}
0 0
- 最长递增子序列(编程之美2.16)
- 编程之美2.16 最长递增子序列
- 编程之美2.16最长递增子序列
- 编程之美2.16-最长递增子序列(Longest Subsequence)
- 编程之美之最长递增子序列实现
- 最长递增子序列编程之美232算法
- [编程之美]求数组中最长递增子序列
- 编程之美 求数组中的最长递增子序列
- 编程之美----数组的最长递增子序列
- 编程之美--求数组中最长递增子序列
- 编程之美--求数组中最长递增子序列
- 最长递增子序列(编程之美)
- 读书笔记之编程之美 - 2.16 求数组中最长递增子序列
- 编程之美读书笔记之2.16求数组中最长递增子序列
- 编程之美: 第二章 数字之魅 2.16求数组中最长递增子序列
- 《编程之美》读书笔记17: 2.16 求数组中最长递增子序列
- 编程之美2.16 求数组中最长递增子序列
- 编程之美2.16——求数组中最长递增子序列
- LeetCode 14 Longest Common Prefix
- mybatis (1) --快速入门
- JS获取当前周、上一周、下一周日期
- java服务器应答例子(用telnet方法测试)
- ImageLoader工具类
- 编程之美2.16最长递增子序列
- 机器学习:防止过拟合的方法
- HDU1180 诡异的楼梯
- 单词王上线了
- POJ 2752
- NSMethodSignature和NSInvocation
- 转-思维要裂变要敢闯想
- wstring
- (十)【续】网络框架篇(RxJava+OkHttp+Gson)