|
| 1 | +class Solution { |
| 2 | + int[] smallerRight; |
| 3 | + public List<Integer> countSmaller(int[] nums) { |
| 4 | + int n = nums.length; |
| 5 | + int[] indexes = new int[n]; |
| 6 | + smallerRight = new int[n]; |
| 7 | + for (int i = 0; i < n; i++) { |
| 8 | + indexes[i] = i; |
| 9 | + } |
| 10 | + mergeSort(nums, indexes, 0, n-1); |
| 11 | + List<Integer> res = new ArrayList<Integer>(); |
| 12 | + for (int i = 0; i < n; i++) { |
| 13 | + res.add(smallerRight[i]); |
| 14 | + } |
| 15 | + return res; |
| 16 | + } |
| 17 | + |
| 18 | + public void mergeSort(int[] nums, int[] indexes, int start, int end) { |
| 19 | + if (end <= start) return; |
| 20 | + int mid = (end+start)/2; |
| 21 | + |
| 22 | + mergeSort(nums, indexes, start, mid); |
| 23 | + mergeSort(nums, indexes, mid+1, end); |
| 24 | + merge(nums, indexes, start, end); |
| 25 | + } |
| 26 | + |
| 27 | + public void merge(int[] nums, int[] indexes, int start, int end) { |
| 28 | + int[] sortArr = new int[end - start + 1]; |
| 29 | + int sortIndex = 0, rightCount = 0, mid = (start+end)/2, left = start, right = mid+1; |
| 30 | + |
| 31 | + while (left <= mid && right <= end) { |
| 32 | + if (nums[indexes[left]] > nums[indexes[right]]) { |
| 33 | + rightCount++; |
| 34 | + sortArr[sortIndex] = indexes[right++]; |
| 35 | + } else { |
| 36 | + smallerRight[indexes[left]] += rightCount; |
| 37 | + sortArr[sortIndex] = indexes[left++]; |
| 38 | + } |
| 39 | + sortIndex++; |
| 40 | + } |
| 41 | + |
| 42 | + while (right <= end) { |
| 43 | + sortArr[sortIndex++] = indexes[right++]; |
| 44 | + } |
| 45 | + while (left <= mid) { |
| 46 | + smallerRight[indexes[left]] += rightCount; |
| 47 | + sortArr[sortIndex++] = indexes[left++]; |
| 48 | + } |
| 49 | + for (int i = start; i <= end; i++) { |
| 50 | + indexes[i] = sortArr[i-start]; |
| 51 | + } |
| 52 | + |
| 53 | + } |
| 54 | +} |
0 commit comments