You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
这道题与307. Range Sum Query – Mutable 类似,可以用 Fenwick Tree (Binary Indexed Tree) 这种特殊的数据结构来处理。具体参考 Fenwick Tree
首先定义 Fenwick Tree 的类:
int query(int i); 方法用来查找第i个节点的prefix sum,求 prefix sum 的过程是沿着一条路径(如图),每次 i -= i & -i; 并将 prefix sum 累加。
void update(int i, int delta); 方法用来动态更新第i个节点的值sums[i],以及受它影响的其他节点的值(如图),至于是哪些节点(哪些 index)受影响,操作跟query相反,每次i += i & -i;并更改sums[i].
classFenwickTree {
privateint[] sums;
publicFenwickTree(intn) {
sums = newint[n + 1];
}
publicvoidupdate(inti, intdelta) {
while (i < sums.length) {
sums[i] += delta;
i += lowbit(i); // i += i & -i;
}
}
publicintquery(inti) {
intsum = 0;
while (i > 0) {
sum += sums[i];
i -= lowbit(i); // i += i & -i;
}
returnsum;
}
}
然后,根据题意,我们要求解 [5, 2, 6, 1] 中,比自己要小的后续数字个数 (smaller numbers after self),第一个数是5,后面的2、1比5小,所以有2个;第二个数是2,后面的1比2小,有1个;以此类推。
题目
这道题与307. Range Sum Query – Mutable 类似,可以用 Fenwick Tree (Binary Indexed Tree) 这种特殊的数据结构来处理。具体参考 Fenwick Tree
首先定义 Fenwick Tree 的类:
int query(int i);
方法用来查找第i个节点的prefix sum,求 prefix sum 的过程是沿着一条路径(如图),每次i -= i & -i;
并将 prefix sum 累加。void update(int i, int delta);
方法用来动态更新第i个节点的值sums[i]
,以及受它影响的其他节点的值(如图),至于是哪些节点(哪些 index)受影响,操作跟query相反,每次i += i & -i;
并更改sums[i]
.然后,根据题意,我们要求解 [5, 2, 6, 1] 中,比自己要小的后续数字个数 (smaller numbers after self),第一个数是5,后面的2、1比5小,所以有2个;第二个数是2,后面的1比2小,有1个;以此类推。
基本思路:
完整代码:
The text was updated successfully, but these errors were encountered: