Leetcode315——Count of Smaller Numbers After Self

来源:互联网 发布:mac开发工具 编辑:程序博客网 时间:2024/05/18 10:04

终于在bst标签下找到一个lz能用bst做的出来的题目,泪目跪谢感谢扶起了我的自尊心,直接上代码,很简单的,就是逆序对的求法。


class Solution {public:    struct node{        int num, count;        node *l, *r;        node(int num): num(num), count(0), l(NULL), r(NULL) {}    };        int Insert(node *&root, int num){        int ans = 0;        if(root == NULL) root = new node(num);        else{            if(num >= root->num){                ans += num == root->num? root->count : root->count + 1;                ans += Insert(root->r, num);            }            else{                root->count++;                ans += Insert(root->l, num);            }        }        return ans;    }        vector<int> countSmaller(vector<int>& nums) {        int n = (int)nums.size();        vector<int> ans(n, 0);        node* root = NULL;                for(int i = n-1; i>=0; i--){            ans[i] = Insert(root, nums[i]);        }                return ans;    }};


暑假完了,lz体重飙升,什么都不说了去跑步了泪。