因为这些题都是一年前整理的,大概10000行代码,到现在已经忘得差不多了。今天复习了不到20道题,特别注意了下高频和低频的差别,因为精力真的有限,尽量复习高频的。
回忆出几道比较重要的:
1、移除有序数组的重复元素
int removeDupInSortedArray(vector<int>& v, copys){
int index=copys;
for(int i=copys;i<v.size();++i){
if(v[i]!=v[i-copys]){
v[index++]=v[i];
}
}
return index;
}
2、接雨水(经典题)
思路即可
3、多数相加:2sum,3sum,3sumClosest
都可以用排序+左右逼近,但2sum是返回的是下标,要用另外的方法。
4、全排列
1、排序+next_permutation
2、手工实现next_permutation
bool next_permutation(vector<int>& v){
//防御编程
auto cur=next(v.rbegin());
while(cur!=v.rend()&&*cur>*prev(cur)){
cur++;
}
if(cur==v.rend()){
reverse(v.begin(),v.end());
return false;
}
auto pivot=find_if(v.rbegin(),cur,bind1st(less<int>(),*cur));
swap(*cur,*pivot);
reverse(v.rbegin(),cur);
return true;
}
//PS:第11行容易写错,区分find和find_if的区别,以及less
5、康拓编解码
6、求两个有序数组中第K个数,时间复杂度为log(m+n)
int getKthTwoSortedArray(vector<int>::iterator& A, int m, vector<int>::iterator& B, int n, int k){
if(m>n) return getKthTwoSortedArray(B,n,A,m,k);
if(m==0) return *(B+k-1);
if(k==1) return min(*A,*B);
int ai=min(k/2,m);
int bi=k-ai;
if(*(A+ai-1)<*(B+bi-1))
return getKthTwoSortedArray(A+ai,m-ai,B,n,k-ai);
else if(*(B+bi-1)<*(A+ai-1))
return getKthTwoSortedArray(A,m,B+bi,n-bi,k-bi);
else
return *(A+ai-1);
}