题目详情
给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
示例:
输入: [5,2,6,1]
输出: [2,1,1,0]
解释:
5 的右侧有 2 个更小的元素 (2 和 1).
2 的右侧仅有 1 个更小的元素 (1).
6 的右侧有 1 个更小的元素 (1).
1 的右侧有 0 个更小的元素.
——题目难度:困难
-解题代码
struct SegmentTreeNode {
int start;
int end;
int count;
SegmentTreeNode* left;
SegmentTreeNode* right;
SegmentTreeNode(int _start, int _end):start(_start),end(_end),count(0) {
left = NULL;
right = NULL;
}
};
class Solution {
public:
SegmentTreeNode* build(int min, int max) {
SegmentTreeNode* root = new SegmentTreeNode(min, max);
if (min != max) {
int mid = min + (max - min) / 2;
root->left = build(min, mid);
root->right = build(mid+1, max);
}
return root;
}
int count(SegmentTreeNode* root, int start, int end) {
if (start > end) return 0;
if (root->start == start && root->end == end) {
return root->count;
}
int mid = root->start + (root->end - root->start) / 2;
int leftcount = 0, rightcount = 0;
if (start <= mid) {
if (end > mid)
leftcount = count(root->left, start, mid);
else
leftcount = count(root->left, start, end);
}
if (end > mid) {
if (start <= mid)
rightcount = count(root->right, mid + 1, end);
else
rightcount = count(root->right, start, end);
}
return leftcount + rightcount;
}
void insert(SegmentTreeNode* root, int num) {
if (root->start == num && root->end == num) {
root->count++;
return ;
}
int mid = root->start + (root->end - root->start) / 2;
if (num <= mid)
insert(root->left, num);
if (num > mid)
insert(root->right, num);
root->count = root->left->count + root->right->count;
}
vector<int> countSmaller(vector<int>& nums) {
vector<int> ans;
if (nums.empty()) return ans;
int minNum = nums[0], maxNum = nums[0], n = nums.size();
ans.resize(n);
for(int i = 1; i < n; i++) {
minNum = min(minNum, nums[i]);
maxNum = max(maxNum, nums[i]);
}
SegmentTreeNode* root = build(minNum, maxNum);
for(int i = n - 1; i >= 0; i--) {
ans[i] = count(root, minNum, nums[i] - 1); //找[min, nums[i] - 1]的元素个数,也就是小于 nums[i] 的元素个数
insert(root, nums[i]);
}
return ans;
}
};
结果