题目地址:
https://www.lintcode.com/problem/count-of-smaller-numbers-after-self/description
给定一个长 n n n数组 A A A,要求返回一个数组 B B B使得 B [ i ] B[i] B[i]等于 A [ i ] A[i] A[i]右边且比 A [ i ] A[i] A[i]小的数字个数。
可以用树状数组。做法可以参考:https://blog.youkuaiyun.com/qq_46105170/article/details/108429714。代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
class FenwickTree {
private int[] tree;
private int n;
public FenwickTree(int n) {
tree = new int[n + 1];
}
public int query(int i) {
int res = 0;
while (i > 0) {
res += tree[i];
i -= lowbit(i);
}
return res;
}
public void add(int i, int x) {
while (i < tree.length) {
tree[i] += x;
i += lowbit(i);
}
}
private int lowbit(int x) {
return x & -x;
}
}
/**
* @param nums: a list of integers
* @return: return a list of integers
*/
public List<Integer> countSmaller(int[] nums) {
// write your code here
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for (int num : nums) {
max = Math.max(max, num);
min = Math.min(min, num);
}
FenwickTree tree = new FenwickTree(max - min + 1);
List<Integer> res = new ArrayList<>();
for (int i = nums.length - 1; i >= 0; i--) {
tree.add(nums[i] - min + 1, 1);
res.add(tree.query(nums[i] - min));
}
Collections.reverse(res);
return res;
}
}
时间复杂度 O ( n log ( m a x − m i n ) ) O(n\log (max-min)) O(nlog(max−min)),空间 O ( m a x − m i n ) O(max-min) O(max−min)。