BIT-逆序数
2019-12-17 09:42:44
问题描述:
问题求解:
逆序数问题非常经典,使用树状数组可以高效的解决这个问题。
public List<Integer> countSmaller(int[] nums) { List<Integer> res = new ArrayList<>(); int n = nums.length; int[] nums_copy = Arrays.copyOf(nums, n); Map<Integer, Integer> map = new HashMap<>(); Arrays.sort(nums_copy); int rank = 0; for (int i = 0; i < n; i++) { if (i == 0 || nums_copy[i] != nums_copy[i - 1]) { map.put(nums_copy[i], ++rank); } } int[] bit = new int[map.size() + 1]; for (int i = n - 1; i >= 0; i--) { update(bit, map.get(nums[i])); res.add(query(bit, map.get(nums[i]) - 1)); } Collections.reverse(res); return res; } private void update(int[] bit, int idx) { for (int i = idx; i < bit.length; i += i & -i) { bit[i] += 1; } } private int query(int[] bit, int idx) { int res = 0; for (int i = idx; i > 0; i -= i & -i) { res += bit[i]; } return res; }