c++ 15 lines O(nlogn) solution

  • 0

    Create a sorted vector of nums, named clac. Starting from nums[0], binary search the position of nums[0] in calc(lower_bound). The position is the number of smaller numbers in nums on the right. Remove the value in calc and proceed to next value nums[1]. Vise versa

    class Solution {
        vector<int> countSmaller(vector<int>& nums) {
            vector<int> calc(nums);
            vector<int> retval(nums.size());
            sort(calc.begin(), calc.end());
            vector<int>::iterator it;
            for (int idx = 0; idx < nums.size(); idx++) {
                it = lower_bound(calc.begin(), calc.end(), nums[idx]);
                retval[idx] = it - calc.begin();
            return retval;

Log in to reply

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