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


struct Node
{
    int val;
    Node *left;
    Node *right;
    int numEqual;
    int numLess;
    Node(int a) : val(a), left(NULL), right(NULL), numEqual(1), numLess(0)
    {}
};

class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) {
        int n = nums.size();
        vector<int> result(n);
        if (n < 1)
        {
            return result;
        }
        result[n-1] = 0;
        Node *root = new Node(nums[n-1]);
        for (int i = n-2; i >= 0; i--)
        {
            int count = 0;
            visit(root, nums[i], count);
            result[i] = count;
        }

        return result;
    }
private:
    void visit(Node *root, int v, int &count)
    {
        if (v < root->val)
        {
            root->numLess++;
            if (root->left != NULL)
            {
                visit(root->left, v, count);
            }
            else
            {
                root->left = new Node(v);
            }
        }
        else if (v > root->val)
        {
            count += root->numEqual + root->numLess;
            if (root->right != NULL)
            {
                visit(root->right, v, count);
            }
            else
            {
                root->right = new Node(v);
            }
        }
        else
        {
            count += root->numLess;
            root->numEqual++;
        }
    }
};


你可能感兴趣的:(Count of Smaller Numbers After Self)