Count of Smaller Numbers After Self

Count of Smaller Numbers After Self 题解


题目描述

Count of Smaller Numbers After Self
即对一个数组中全部元素,找出右边小于自身的元素的个数。
如:[5,2,1,1]
返回[3,2,0,0]数组

题解

能够遍历元素右边的元素,进行比较并记录小于其的元素个数。时间复杂度为线性。若想下降复杂度,可经过二分查找思想下降到O(log n)。由于会随机插入,因此采起二叉搜索树进行记录。spa

代码

#include <vector>

typedef int _Type;

class Solution {
public:
    typedef struct Node {
        _Type val;
        size_t leftChild;
        struct Node *left, *right;
    } Node;

    void freeTree(Node* p) {
        if (p == NULL)
            return;
        freeTree(p->left);
        freeTree(p->right);
        free(p);
    }

    size_t insert(Node* & p, _Type val) {
        if (p == NULL) {
            p = (Node*)malloc(sizeof(Node));
            p->val = val;
            p->left = p->right = NULL;
            return p->leftChild = 0U;
        }
        if (p->val < val)
            return (p->leftChild) + 1 + insert(p->right, val);
        if (p->val == val)
            return (p->leftChild) + insert(p->right, val);
        ++(p->leftChild);
        return insert(p->left, val);
    }

    std::vector<int> countSmaller(std::vector<int>& nums) {
        std::vector<int> vec(nums.size());
        Node* root = NULL;
        for (int i = nums.size() - 1; i >= 0; --i)
            vec[i] = insert(root, nums[i]);
        freeTree(root);
        return vec;
    }
};

总结

主要应用了二分查找思想。code

相关文章
相关标签/搜索