二分搜索,边界条件要注意
public class Solution { public List<Integer> countSmaller(int[] nums) { List<Integer> sorted = new ArrayList<Integer>(); int length = nums.length; List<Integer> result = new LinkedList<Integer>(); for (int i = length - 1; i >= 0; i--) { int num = helper(sorted, nums[i]); result.add(0, num); } return result; } private int helper(List<Integer> sorted, int num) { int left = 0; int size = sorted.size(); if (size == 0) { sorted.add(num); return 0; } else if (num > sorted.get(size - 1)) { sorted.add(size, num); return size; } int right = size - 1; while (left + 1 < right) { int mid = left + (right - left) / 2; if (sorted.get(mid) >= num) { right = mid; } else { left = mid; } } int tmp = sorted.get(left) >= num ? left : right; sorted.add(tmp, num); return tmp; } }