题目:
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].
这个题和Leetcode 327. Count of Range Sum[hard](http://blog.csdn.net/qq379548839/article/details/52601135)很像,也可以用相同的做法:再平衡树中倒叙插入数组中的每个数字,在插入时可以计算出之前插入的小于这个数字的数字个数,即为counts。同样的,也可以用离散化+树状数组。
但有一种新的方法:分治。
将数组分成左右两个部分,则左边部分一个数字lx对应的答案=右边部分比lx小的数字的个数+左边部分内部lx右边比lx小的数字个数;右边部分一个数字rx对应的答案=右边部分内部rx右边比rx小的数字个数。
而这个程类可以在归并排序过程中轻易实现。
同样的,这种分治方法同样可以用在Leetcode 327. Count of Range Sum[hard]中~
注意:这个题有个坑,传入的nums可能为空。答案需要特判一下。
class Solution {
public:
vector<int> v;
vector<int> cnt;
vector<int> s;
vector<int> countSmaller(vector<int>& nums) {
v.clear();
cnt.clear();
if (nums.size() == 0) return cnt;
for (int i = 0; i < nums.size(); i++) cnt.push_back(0);
for (int i = 0; i < nums.size(); i++) v.push_back(i);
calc(nums, 0, nums.size() - 1);
return cnt;
}
void calc(vector<int>& nums, int lt, int rt) {
if (lt == rt) return;
int x = (lt + rt) / 2;
calc(nums, lt, x);
calc(nums, x + 1, rt);
s.clear();
int pa = lt, pb = x + 1;
while (pa <= x || pb <= rt) {
if (pa > x) {
s.push_back(v[pb]);
pb++;
//if (lt == 0 && rt == 3) cout << "a" << endl;
}
else if (pb > rt) {
s.push_back(v[pa]);
cnt[v[pa]] += pb - (x + 1);
pa++;
//if (lt == 0 && rt == 3) cout << "b" << endl;
}
else {
if (nums[v[pa]] <= nums[v[pb]]) {
s.push_back(v[pa]);
cnt[v[pa]] += pb - (x + 1);
pa++;
//if (lt == 0 && rt == 3) cout << "c" << endl;
}
else {
s.push_back(v[pb]);
pb++;
//if (lt == 0 && rt == 3) cout << "d" << endl;
}
}
}
for (int i = 0; i < s.size(); i++) v[i + lt] = s[i];
return;
}
};