249 · 统计前面比自己小的数的个数

 

链接:九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧

LintCode 炼码

复杂链式结构:跳表_INGNIGHT的博客-CSDN博客:块状链表

class Solution {
private:
    class BlockManager {
    struct Block {
        int total;
        std::vector<int> count;
        Block(int block_size):total(0) {
            count.resize(block_size);
        }
    };
    public:
        BlockManager(int capicaty) {
            _block_size = sqrt(capicaty);
            int block_count = capicaty / _block_size;
            _blocks.reserve(block_count);
            for (int i = 0; i < block_count; ++i) {
                _blocks.emplace_back(Block(_block_size));
            }
        }
    private:
        std::vector<Block> _blocks;
        int _block_size;
    public:
        int get_count(int val) {
            int index = val / _block_size;
            int offset = val % _block_size;
            int count = 0;
            for (int i = 0; i < index; ++i) {
                count += _blocks[i].total;
            }
            for (int i = 0; i < offset; ++i) {
                count += _blocks[index].count[i];
            }
            return count;
        }
        void insert(int val) {
            int index = val / _block_size;
            int offset = val % _block_size;
            ++_blocks[index].total;
            ++_blocks[index].count[offset];
        }
    };
public:
    /**
     * @param a: an integer array
     * @return: A list of integers includes the index of the first number and the index of the last number
     */
    vector<int> countOfSmallerNumberII(vector<int> &a) {
        // write your code here
        if (a.size() <= 0) {
            return {};
        }
        std::vector<int> result;
        result.reserve(a.size());
        BlockManager mgr(100000);
        for (auto num : a) {
            result.push_back(mgr.get_count(num));
            mgr.insert(num);
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值