class Solution {
public:
struct SegmentTreeNode {
SegmentTreeNode* left, *right;
int start, end;
int count;
SegmentTreeNode(int start, int end, int count)
: start(start), end(end), count(count) {
left = right = NULL;
}
};
SegmentTreeNode* (int start, int end) {
if (start > end) return NULL;
SegmentTreeNode* root = new SegmentTreeNode(start, end, 0);
if (start != end) {
int mid = start + (end - start) / 2;
root->left = build(start, mid);
root->right = build(mid+1, end);
}
return root;
}
int querySegmentTree(SegmentTreeNode* root, int start, int end) {
if (root->start == start && root->end == end)
return root->count;
int leftcount = 0, rightcount = 0;
int mid = root->start + (root->end - root->start) / 2;
if (start <= mid) {
if (mid < end) {
leftcount = querySegmentTree(root->left, start, mid);
} else {
leftcount = querySegmentTree(root->left, start, end);
}
}
if (mid < end) {
if (start <= mid) {
rightcount = querySegmentTree(root->right, mid+1, end);
} else {
rightcount = querySegmentTree(root->right, start, end);
}
}
return leftcount + rightcount;
}
void modifySegmentTree(SegmentTreeNode* root, int index, int value) {
if (root->start == index && root->end == index) {
root->count += value;
return ;
}
int mid = root->start + (root->end - root->start) / 2;
if (root->start <= index && index <= mid) {
modifySegmentTree(root->left, index, value);
}
if (mid < index && index <= root->end) {
modifySegmentTree(root->right, index, value);
}
root->count = root->left->count + root->right->count;
}
vector<int> countSmaller(vector<int>& nums) {
vector<int> ret;
SegmentTreeNode* root = build(-1000, 10000);
for (int i=nums.size()-1; i>=0; i--) {
int ans = querySegmentTree(root, -1000, nums[i]-1);
modifySegmentTree(root, nums[i], 1);
ret.push_back(ans);
}
reverse(ret.begin(), ret.end());
return ret;
}
};
近期评论