给定一个整数数组nums,返回一个新的counts数组。counts[i]表示:nums[i]右侧比它小的数的个数。
比较好的算是是用Binary Indexed Tree, 不过我觉得掌握普通的binary search已经勉强够用了,不追求高难度的话就把下面的普通解法扎实写好就行
binary search一次bug free写好秘诀:
把一些常见case代进去试试:
+当前list为空的情况
+集合里只有一个数的情况
+当前Mid的值跟target相等的情况
+target值应该排在最前和最后的情况
。。。
这些情况下,代进去看:
+最后跳出循环的start是多少
+最后跳出循环的end是多少
+insert的位置或者返回的index值对不对
public List<Integer> countSmaller(int[] a) {
if(a == null || a.length == 0) return new ArrayList();
//int[] res = new int[a.length];
List<Integer> later = new ArrayList<Integer>(a.length); //集合初始化最好都附上集合大小
List<Integer> result = new ArrayList(a.length);
for(int i=a.length-1; i>=0;i--) {
result.add(0, insert(later, a[i]));
}
//return Arrays.stream(res).boxed().collect(Collectors.toList());
return result;
}
private int insert(List<Integer> list, int x) {
int start = 0, end = list.size() -1;//binary search一次bug free写好秘诀
while(start <= end) { //把当前list为空的情况代进去试试,集合里只有一个数的情况
int mid = start + (end - start)/2;
if(list.get(mid) >= x) { //把握好相等的情况
end = mid -1;
} else {
start = mid + 1;
}
}
list.add(start, x);
return start;
}