BIT-Reverse Pairs
2019-12-17 11:07:02
问题描述:
问题求解:
本题可以看作是逆序数问题的强化版本,需要注意的是num[i] > 2 * num[j],这里有0和负数的情况。
public int reversePairs(int[] nums) { int res = 0; int n = nums.length; int[] nums_copy = Arrays.copyOf(nums, n); TreeMap<Integer, Integer> map = new TreeMap<>(); 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--) { int num = nums[i] % 2 == 0 ? nums[i] / 2 - 1 : (nums[i] - 1) / 2; Integer key = map.floorKey(num); if (key != null) res += query(bit, map.get(key)); update(bit, map.get(nums[i])); } 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; }