期末终于结束了额。
第一次写分治。
这个题是用结构体储存分治过程中,此元素右边较小元素的个数。
第一次WA:分支过程中,在元素p右边比元素p更小的元素个数为q-m。但是在过程中有很多这样的元素,所以应该+=,而不应该=。
第二次WA:判断q的位置的时候,是a[p]<=a[q]就将q-m加到p.v上。因为这个题是要求小于,所以大于等于就是它的互斥条件。
除此之外,分治还有很多细节需要熟悉。
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
if(nums.empty()) {
return nums;
}
else{
int l=nums.size();
val temp[l];
for(int i=0;i<l;i++){
temp[i].shu=nums[i];
temp[i].pos=i;
temp[i].v=0;
}
val fu[l];
sort1(temp,0,l,fu);
vector<int> ct(l);
for(int i=0;i<l;i++){
ct[temp[i].pos]=temp[i].v;
}
return ct;
}
}
struct val{
int pos;
int v;
int shu;
bool operator < (val a) const{
return this->shu < a.shu;
}
bool operator <= (val a) const{
return (this->shu <= a.shu);
}
};
void sort1(val *a,int x,int y,val *t){
if(y-x>1){
int m=x+(y-x)/2;
sort1(a,x,m,t);
sort1(a,m,y,t);
int p=x,q=m,i=x;
while(p<m||q<y){
if(q>=y||(p<m&&a[p]<=a[q])){
a[p].v+=q-m;
t[i++]=a[p++];
}
else{
t[i++]=a[q++];
}
}
for(int i=x;i<y;i++){
a[i]=t[i];
}
}
}
};