LeetCode 315. Count of Smaller Numbers After Self

题意:

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].

思路:

排序、树状数组。 注意树状数组,从0开始, 注意max。

lobit(x) = x& ( x^(x-1) ),我居然忘了哈~~~

AC代码:

class Solution {
public:
    int total = 0;
    int lobit(int x)
    {
        return x&( x^(x-1) );
    }
    void add(int pos, int val, vector<int> & sum)
    {
        while(pos<=total)
        {
            sum[pos] += val;
            pos += lobit(pos);
        }
    }
    int get(int pos, vector<int> & sum)
    {
        int ret = 0;
        while(pos)
        {
            ret += sum[pos];
            pos -= lobit(pos);
        }
        return ret;
    }
    
    vector<int> countSmaller(vector<int>& nums) {
        int n = nums.size();
        vector<int> temp;
        for(int i=0; i<nums.size(); i++)
        {
            temp.push_back(nums[i]);
        }
        sort(temp.begin(), temp.end());
        map<int,int>mp;
        for(int i=0; i<temp.size(); i++)
            mp[temp[i]] = i+2;
        
        vector<int> sum(n+10, 0);
        total = n+5;
        vector<int> ret;
        for(int i=nums.size()-1; i>=0; --i)
        {
            ret.push_back( get(mp[nums[i]]-1, sum) );
            add(mp[nums[i]], 1, sum);
        }
        for(int i=0; i<nums.size()/2; i++)
        {
            swap(ret[i], ret[ret.size()-1-i]);
        }
        return ret;
    }
};

 

posted @ 2016-03-21 22:27  Gu Feiyang  阅读(139)  评论(0)    收藏  举报