Simple and clean 48ms C++ solution using just vectors


  • 1
    R
    vector<int> countSmaller(const vector<int>& nums) 
    {
        vector<pair<int,int>> pv(nums.size());
        vector<int> counter(nums.size(), 0);
        vector<int> result(nums.size(), 0);
        for (int i=0; i < nums.size(); i++)
        {
            pv[i] = {nums[i], i};
        }
        sort(pv.begin(), pv.end());
        
        for (auto p : pv)
        {
            int left=0, right=nums.size(), total=0;
            
            while ( left < right)
            {
                int m = (left+right)/2;
                if (m > p.second)
                {
                    total += counter[m];
                    right=m;
                }
                else if (m < p.second)
                {
                    ++counter[m];
                    left = m;
                }
                else 
                {
                    total += counter[m];
                    ++counter[m];
                    break;
                }
                    
            }
            result[p.second] = total;  
        }
     
        return result;
    }
    

    The idea is base on walking and marking the same path as in binary search.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.