Count of Smaller Numbers After Self 题解
题目描述
即对一个数组中所有元素,找出右边小于自身的元素的个数。
如:[5,2,1,1]
返回[3,2,0,0]
题解
可以遍历元素右边的元素,进行比较并记录小于其的元素个数。时间复杂度为线性。若想降低复杂度,可通过二分查找思想降低到O(log n)。因为会随机插入,所以采取二叉搜索树进行记录。
代码
#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;
}
};
总结
主要应用了二分查找思想。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。