Leetcode 315. Count of Smaller Numbers After Self[hard]

题目:
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].


这个题和Leetcode 327. Count of Range Sum[hard](http://blog.csdn.net/qq379548839/article/details/52601135)很像,也可以用相同的做法:再平衡树中倒叙插入数组中的每个数字,在插入时可以计算出之前插入的小于这个数字的数字个数,即为counts。同样的,也可以用离散化+树状数组。

但有一种新的方法:分治。

将数组分成左右两个部分,则左边部分一个数字lx对应的答案=右边部分比lx小的数字的个数+左边部分内部lx右边比lx小的数字个数;右边部分一个数字rx对应的答案=右边部分内部rx右边比rx小的数字个数。
而这个程类可以在归并排序过程中轻易实现。

同样的,这种分治方法同样可以用在Leetcode 327. Count of Range Sum[hard]中~

注意:这个题有个坑,传入的nums可能为空。答案需要特判一下。

这里写图片描述

class Solution {
public:
    vector<int> v;
    vector<int> cnt;
    vector<int> s;
    vector<int> countSmaller(vector<int>& nums) {
        v.clear();
        cnt.clear();
        if (nums.size() == 0) return cnt;
        for (int i = 0; i < nums.size(); i++) cnt.push_back(0);
        for (int i = 0; i < nums.size(); i++) v.push_back(i);
        calc(nums, 0, nums.size() - 1);
        return cnt;
    }

    void calc(vector<int>& nums, int lt, int rt) {
        if (lt == rt) return;
        int x = (lt + rt) / 2;
        calc(nums, lt, x);
        calc(nums, x + 1, rt);
        s.clear();
        int pa = lt, pb = x + 1;
        while (pa <= x || pb <= rt) {
            if (pa > x) {
                s.push_back(v[pb]);
                pb++;
                //if (lt == 0 && rt == 3) cout << "a" << endl;
            }
            else if (pb > rt) {
                s.push_back(v[pa]);
                cnt[v[pa]] += pb - (x + 1);
                pa++;
                //if (lt == 0 && rt == 3) cout << "b" << endl;
            }
            else {
                if (nums[v[pa]] <= nums[v[pb]]) {
                    s.push_back(v[pa]);
                    cnt[v[pa]] += pb - (x + 1);
                    pa++;
                    //if (lt == 0 && rt == 3) cout << "c" << endl;
                }
                else {
                    s.push_back(v[pb]);
                    pb++;
                    //if (lt == 0 && rt == 3) cout << "d" << endl;
                }
            }
        }
        for (int i = 0; i < s.size(); i++) v[i + lt] = s[i];
        return;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值