原题:
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:
Input: [5,2,6,1]
Output: [2,1,1,0]
Explanation:
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.
大致题意:
给定一个整数数组,返回一个新的数组使每位都记录原数组该位置的数右侧有多少个更小的数。
一开始没有特别好的思路,感觉应该是用线段树来解决,后来查了一下网上发现用Binary Indexed Tree(树状数组)更简单。九章上面用了同样的方法不过没有写出BIT的类,感兴趣的话可以去看看。
大致思路就是,先离散化整个数组(排序后二分查找返回对应位置的index,比较蠢,应该有更好的写法),用一个树状数组去逆向query+update整个数组即可。其中利用了树状数组每次update和query都是log级别,加上排序和二分查找,总体时间复杂度是O(nlogn), 空间复杂度O(n)。
其中要注意的细节就是,树状数组相当于是1-index的,而正常数组是0-index的。
代码如下,应该还有的地方可以优化:
class BIT {
public:
BIT(int size) : n(size + 1), sums(n + 1, 0) {};
void update(int i, int d) {
i++;
while (i <= n) {
sums[i] += d;
i += lowbit(i);
}
}
int query(int i) {
i++;
int ans = 0;
while (i > 0) {
ans += sums[i];
i -= lowbit(i);
}
return ans;
}
private:
static inline int lowbit(int x) { return x & (-x); }
int n;
vector<int> sums;
};
class Solution {
public:
/**
* @param nums: a list of integers
* @return: return a list of integers
*/
vector<int> countSmaller(vector<int> &nums) {
// write your code here
int n = nums.size();
vector<int> res(n, 0);
if (n == 0) {
return res;
}
descretize(nums);
tree = new BIT(n);
for (int i = n - 1; i >= 0; i--) {
res[i] = tree->query(nums[i] - 1);
tree->update(nums[i], 1);
}
return res;
}
private:
void descretize(vector<int> &nums) {
vector<int> sorted(nums.begin(), nums.end());
sort(sorted.begin(), sorted.end());
for (int &num : nums) {
num = bs(num, sorted);
}
}
int bs(int num, vector<int> &nums) {
int l = 0, r = nums.size() - 1;
while (l + 1 < r) {
int mid = l + (r - l) / 2;
if (nums[mid] == num) {
return mid;
} else if (nums[mid] > num) {
r = mid;
} else {
l = mid;
}
}
return nums[l] == num ? l : r;
}
BIT* tree;
};
树状数组视频可以戳油管上花花酱的视频,个人觉得讲的还行:
https://www.youtube.com/watch?v=WbafSgetDDk&t=847s
第一次在leetcode上面击败了100%的submission。。。