[LeetCode] 315

来源:互联网 发布:利用广告联盟做淘宝客 编辑:程序博客网 时间:2024/05/16 09:16

315. Count of Smaller Numbers After Self


题目:给定一个数列,返回vector<int> count, count[i] 代表 nums 中在nums[i] 之后且比nums[i] 小的数字的个数


思路:建立BST,每个节点除了左右child之外增加一个int l代表数组中比l小的数的数量。

从后往前遍历数组,把每个数字插入BST的时候统计比它小的数字的个数

如果root->val >= a, 那么插入左子树,root->l++

如果root->val < a, 那么插入右子树,ans += root->l

当数字被插入时返回ans的数字

struct Node{        Node* left;        Node* right;        int val;        int l;        Node(int x) : val(x), left(NULL), right(NULL), l(0) {}};    void insert(Node* & root, int a , int & ans){        if(root == NULL)        {                root = new Node(a);                return;        }        if(root->val >= a)        {                root->l++;                insert(root->left, a, ans);        }        else        {                ans +=  root->l+1;                insert(root->right, a, ans);        }}vector<int> countSmaller(vector<int> &nums){        int n = nums.size();        if(n == 0) return vector<int>();        vector<int> result(nums.size(), 0);        Node* root = new Node(nums[n-1]);        for(int i = n-2; i >= 0; i--)        {                int ans = 0;                insert(root, nums[i] , ans);                result[i] = ans;        }        return result;}


0 0