C++ 49ms


  • 0
    class Solution {
    public:
        vector<int> countSmaller(vector<int>& nums) {
            vector<int> s;
            vector<int> ans;
            for(int i=nums.size()-1;i>=0;i--) {
                if(s.empty()) {
                    s.push_back(nums[i]);
                    ans.push_back(0);
                    continue;
                }
                int l=0, r = s.size()-1;
                while(l<=r) {
                    int mid = (l+r)/2;
                    if(s[mid] < nums[i]) {
                        l = mid+1;    
                    } else r= mid-1;
                }
                s.insert(s.begin()+l,nums[i]);
                ans.push_back(l);
            }
            reverse(ans.begin(),ans.end());
            return ans;
        }
    };
    

Log in to reply
 

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