Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Almost identical to LintCode "Count of Smaller Number before Self". Corner case needs to be taken care of.

class Solution {
    //////////////////
    // Fenwick Tree //
    vector<long long> ft;
    void update(int i, long long x)
    {
        if (i == 0)
        {
            ft[0] ++;
            return;
        }
        if ((i + 1) > ft.size()) return;
        for (; i < ft.size(); i += (i & -i))
            ft[i] += x;
    }

    long long query(int i)
    {
        if (i == 0) return ft[0];

        i = min(i, int(ft.size() - 1));
        long long s = 0;
        for (; i > 0; i -= (i & -i))
            s += ft[i];
        return s + ft[0];
    }
    //////////////////
public:
    vector<int> countSmaller(vector<int>& nums) {
        ft.assign(20000, 0);
        vector<int> ret;
        if(nums.size() < 1) return {};
        //    handling neg
        auto r = minmax_element(nums.begin(), nums.end());
        int minv = *r.first;
        int maxv = *r.second;
        int d = 0;
        vector<long long> ns;
        if (minv < 0)
        {
            d = -minv + 1;
        }
        for (auto v : nums)
            ns.push_back(v + d);
        //
        
        for (int i = ns.size() - 1; i >= 0; i--)
        {
            int v = ns[i];
            int r = query(v - 1);
            update(v, 1);
            ret.push_back(r);
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
};
posted on 2015-12-15 13:55  Tonix  阅读(170)  评论(0编辑  收藏  举报