统计前面比自己小的数的个数-LintCode

给定一个整数数组(下标由 0 到 n-1, n 表示数组的规模,取值范围由 0 到10000)。对于数组中的每个 ai 元素,请计算 ai 前的数中比它小的元素的数量。

注意事项:
We suggest you finish problem Segment Tree Build, Segment Tree Query II and Count of Smaller Number first.

样例:
对于数组[1,2,7,8,5] ,返回 [0,1,2,3,2]

#ifndef C249_H
#define C249_H
#include<iostream>
#include<vector>
using namespace std;
class SegmentNode{
public:
    int start, end, count;
    SegmentNode *left, *right;
    SegmentNode(int start, int end)
    {
        this->start = start, this->end = end, this->count = 0;
        this->left = this->right = NULL;
    }
};
class Solution {
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
        vector<int> v;
        SegmentNode *node = build(0, 10000);
        for (int i = 0; i<A.size(); ++i)
        {
            v.push_back(query(node, 0, A[i] - 1));
            modify(node, A[i]);
        }
        return v;
    }
    SegmentNode *build(int start, int end)
    {
        if (start > end)
            return NULL;
        SegmentNode *node = new SegmentNode(start, end);
        if (start == end)
            return node;
        node->left = build(start, (start + end) / 2);
        node->right = build((start + end) / 2 + 1, end);
        return node;
    }
    void modify(SegmentNode *root, int index)
    {
        if (!root)
            return;
        if (root->start == root->end&&root->start==index)
        {
            root->count++;
            return;
        }
        int mid = (root->start + root->end) / 2;
        if (index<=mid)
            modify(root->left, index);
        else
            modify(root->right, index);
        root->count = root->left->count + root->right->count;
    }
    int query(SegmentNode *root, int start, int end)
    {
        if (start > end || root == NULL || start<root->start || end>root->end)
            return 0;
        if (start == root->start&&end == root->end)
            return root->count;
        if (end <= root->left->end)
            return query(root->left, start, end);
        else if (start >= root->right->start)
            return query(root->right, start, end);
        else
        {
            int l = query(root->left, start, root->left->end);
            int r = query(root->right, root->right->start, end);
            return l + r;
        }
    }
};
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值