1.sort
std::sort
//sort(first,last,compare);
vector<int> s={1,3,5,2,4,6};
//compare可以是默认(不写)、库函数、用户函数、lambda表达式
sort(s.begin(),s.end(),greadter<int>());//递减
sort(s.begin().s.end(),[](int a,int b){return a<b;});//递增
2.pair
std::pair
pair<int,int> s={1,2};
cout<<s.first<<s.second;
3.求最长递增子序列
3.1使用动态规划(O(n^2))
对于第i个数字a[i],若以a[i]为结尾,可求出最长递增子序列长度为
max(以前面每一个数字作结尾的最长递增子序列长度+1(如果a[i]可以放在那个数字后面的话))
比如对于第3个数字,它作结尾的最长递增子序列长度为
max(0)//a[3]<a[1],a[3]<a[2]
max(第1个数字作结尾的长度+1)//a[3]>a[1],a[3]<a[2]
max(第2个数字作结尾的长度+1)//a[3]<a[1],a[3]>a[2]
max(第1个数字作结尾的长度+1,第2个数组做结尾的长度+1)//a[3]>a[1],a[3]>a[2]
有可能超时
3.2二分查找(O(nlogn))
该算法不容易理解
做法:
初始化一个空序列
把每一个数字都插入该序列中:替换序列中第一个大于等于该数字的位置;若序列末尾的数字仍比它小则放在末尾
序列中大于等于一个数字的位置可以用std::lower_bound(Search for first element that is not less than i)做到,这个函数使用二分查找的方式实现
对于序列[1,2,3,4,0,1,2],七个数字插入空数组,每一步之后数组为
[]
[1]
[1,2]
[1,2,3]
[1,2,3,4]
[0,2,3,4]
[0,1,3,4]
[0,1,2,4]
可以看到虽然最终该序列不是答案[1,2,3,4]而是[0,1,2,4],但长度4是没有问题的,而题目仅仅要求最长递增子序列的长度
vector<int> a={1,2,3,4,0,1,2};
vector<int> dp;
for(int x:a){
auto p=lower_bound(dp.begin(),dp.end(),x);
if(p==dp.end()) dp.push_back(x);
else *p=x;
}
return dp.size();