# Hard-题目11：315. Count of Smaller Numbers After Self

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].

C[1]=a[1],c[2]=a[1]+a[2],….c[8]=a[1]+…+a[8],

void add(int* tree,int k,int num) // 在a[k]上增加num，更新树状数组tree
int get(int* tree,int k) // 求a[1]+…+a[k]的和

nums[]=[6,8,1,3],min=1,max=8

public class Solution {
public List<Integer> countSmaller(int[] nums) {
if (nums == null || nums.length == 0) {
return res;
}
// find min value and minus min by each elements, plus 1 to avoid 0 element
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
min = (nums[i] < min) ? nums[i]:min;
}
int[] nums2 = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
nums2[i] = nums[i] - min + 1;
max = Math.max(nums2[i],max);
}
int[] tree = new int[max+1];
for (int i = nums2.length-1; i >= 0; i--) {
update(nums2[i],tree);
}
return res;
}
private int get(int i, int[] tree) {
int num = 0;
while (i > 0) {
num +=tree[i];
i -= i&(-i);
}
return num;
}
private void update(int i, int[] tree) {
while (i < tree.length) {
tree[i] ++;
i += i & (-i);
}
}
}

8ms，beats 97.33%，众数11ms，8.79%
Cmershen的碎碎念：

• 本文已收录于以下专栏：

举报原因： 您举报文章：Hard-题目11：315. Count of Smaller Numbers After Self 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)