|
| 1 | +// o(nlogn) |
| 2 | + |
| 3 | +class Solution { |
| 4 | + public List<Integer> countSmaller(int[] nums) { |
| 5 | + int n = nums.length; |
| 6 | + int[] counts = new int[n]; |
| 7 | + int[] indices = new int[n]; |
| 8 | + for (int i = 0; i < n; i++) indices[i] = i; |
| 9 | + mergeSort(nums, indices, counts, 0, n - 1); |
| 10 | + List<Integer> result = new ArrayList<>(); |
| 11 | + for (int c : counts) result.add(c); |
| 12 | + return result; |
| 13 | + } |
| 14 | + |
| 15 | + private void mergeSort(int[] nums, int[] indices, int[] counts, int left, int right) { |
| 16 | + if (left >= right) return; |
| 17 | + int mid = (left + right) >>> 1; |
| 18 | + mergeSort(nums, indices, counts, left, mid); |
| 19 | + mergeSort(nums, indices, counts, mid + 1, right); |
| 20 | + merge(nums, indices, counts, left, mid, right); |
| 21 | + } |
| 22 | + |
| 23 | + private void merge(int[] nums, int[] indices, int[] counts, int left, int mid, int right) { |
| 24 | + int[] temp = new int[right - left + 1]; |
| 25 | + int i = left, j = mid + 1, k = 0, rightCount = 0; |
| 26 | + while (i <= mid && j <= right) { |
| 27 | + if (nums[indices[j]] < nums[indices[i]]) { |
| 28 | + rightCount++; |
| 29 | + temp[k++] = indices[j++]; |
| 30 | + } else { |
| 31 | + counts[indices[i]] += rightCount; |
| 32 | + temp[k++] = indices[i++]; |
| 33 | + } |
| 34 | + } |
| 35 | + while (i <= mid) { |
| 36 | + counts[indices[i]] += rightCount; |
| 37 | + temp[k++] = indices[i++]; |
| 38 | + } |
| 39 | + while (j <= right) temp[k++] = indices[j++]; |
| 40 | + for (int p = 0; p < temp.length; p++) indices[left + p] = temp[p]; |
| 41 | + } |
| 42 | +} |
0 commit comments