Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new counts array. The counts the array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
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.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int tree[100001], M = 1;
void add(int v)
{
    while (v)
    {
        tree[v]++;
        v >>= 1;
    }
}
int get(int pint kint res = 0)
{
    while (p <= k && p != 0 && k != 0)
    {
        if (p % 2 == 1)
            res += tree[p++];
        if (k % 2 == 0)
            res += tree[k--];
        p >>= 1;
        k >>= 1;
    }
    return res;
}
vector<intcountSmaller(vector<int&nums)
{
    set<ints;
    map<intintm;
    int nr = 0;
    for (auto i : nums)
        s.insert(i);
    for (auto i : s)
        m[i] = nr++;
    while (M < nr)
        M <<= 1;
    for (int i = nums.size() - 1i >= 0i--)
    {
        add(m[nums[i]] + M);
        nums[i] = get(Mm[nums[i]] - 1 + M);
    }
    return nums;
}
int main()
{
    vector<intnums = {5261};

    vector<intres = countSmaller(nums);

    cout << "[";
    for (int i = 0i < res.size(); i++)
    {
        cout << res[i];
        if (i != res.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment