Leetcode 315 计算右侧小于当前元素的个数

期末终于结束了额。

第一次写分治。
这个题是用结构体储存分治过程中,此元素右边较小元素的个数。
第一次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];
            }
        }
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值