https://leetcode-cn.com/problems/count-of-smaller-numbers-after-self/
难度困难
给你一个整数数组 nums ,按要求返回一个新数组 counts 。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
示例 1:
输入:nums = [5,2,6,1]
输出:[2,1,1,0]
解释:
5 的右侧有 2 个更小的元素 (2 和 1)
2 的右侧仅有 1 个更小的元素 (1)
6 的右侧有 1 个更小的元素 (1)
1 的右侧有 0 个更小的元素
示例 2:输入:nums = [-1]
输出:[0]
示例 3:输入:nums = [-1,-1]
输出:[0,0]
提示:
1 <= nums.length <=
- <= nums[i] <=
方法一:树状数组
public static List<Integer> countSmaller(int[] nums) { int len = nums.length; List<Integer> counts = new ArrayList<>(len); //去重 离散化 Set<Integer> set = new TreeSet<>(); for (int num : nums) { set.add(num); } int index = 1; Map<Integer, Integer> map = new HashMap<>(); for (int num : set) { map.put(num, index++); } //BIT int[] tree = new int[index + 1]; //边查询边更新 for (int i = len - 1; i >= 0; i--) { int num = nums[i]; int x = map.get(num); int count = query(tree, x - 1); counts.add(count); update(tree, x); } int left = 0; int right = len - 1; while (left < right) { int temp = counts.get(left); counts.set(left, counts.get(right)); counts.set(right, temp); left++; right--; } return counts; } private static void update(int[] tree, int index) { while (index < tree.length) { tree[index] += 1; index += (index & - index); } } private static int query(int[] tree, int index) { int res = 0; while (index > 0) { res += tree[index]; index -= (index & - index); } return res; }
方法二:归并排序
public static List<Integer> countSmaller(int[] nums) { int len = nums.length; int[] indexs = new int[len]; for (int i = 0; i < len; i++) { indexs[i] = i; } int[] counts = new int[len]; int[] temp = new int[len]; mergeAndCount(nums, indexs, counts, temp, 0, len - 1); List<Integer> list = new ArrayList<>(); for (int num : counts) { list.add(num); } return list; } private static void mergeAndCount(int[] nums, int[] indexs, int[] counts, int[] temp, int left, int right) { if (left == right) return; int mid = left + (right - left) / 2; mergeAndCount(nums, indexs, counts, temp, left, mid); mergeAndCount(nums, indexs, counts, temp, mid + 1, right); int leftPtr = left; int rightPtr = mid + 1; int pointer = left; while (pointer <= right) { if (leftPtr == mid + 1) { temp[pointer++] = indexs[rightPtr++]; }else if (rightPtr == right + 1) { counts[indexs[leftPtr]] += rightPtr - (mid + 1); temp[pointer++] = indexs[leftPtr++]; }else if (nums[indexs[leftPtr]] <= nums[indexs[rightPtr]]) { counts[indexs[leftPtr]] += rightPtr - (mid + 1); temp[pointer++] = indexs[leftPtr++]; }else { temp[pointer++] = indexs[rightPtr++]; } } for (int i = left; i <= right; i++) { indexs[i] = temp[i]; } }