From 4eeaaf208f504497ac2c3c3e9a20acc16c0e6914 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=97=BC=ED=98=9C=EC=A0=95?= <122238744+cyzlcyzl@users.noreply.github.com> Date: Sun, 23 Aug 2026 23:49:26 +0900 Subject: [PATCH] Create 315. Count of Smaller Numbers After Self.java --- ... Count of Smaller Numbers After Self.java" | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 "leetcode3/\354\227\274\355\230\234\354\240\225/315. Count of Smaller Numbers After Self.java" diff --git "a/leetcode3/\354\227\274\355\230\234\354\240\225/315. Count of Smaller Numbers After Self.java" "b/leetcode3/\354\227\274\355\230\234\354\240\225/315. Count of Smaller Numbers After Self.java" new file mode 100644 index 00000000..d60da05b --- /dev/null +++ "b/leetcode3/\354\227\274\355\230\234\354\240\225/315. Count of Smaller Numbers After Self.java" @@ -0,0 +1,42 @@ +// o(nlogn) + +class Solution { + public List countSmaller(int[] nums) { + int n = nums.length; + int[] counts = new int[n]; + int[] indices = new int[n]; + for (int i = 0; i < n; i++) indices[i] = i; + mergeSort(nums, indices, counts, 0, n - 1); + List result = new ArrayList<>(); + for (int c : counts) result.add(c); + return result; + } + + private void mergeSort(int[] nums, int[] indices, int[] counts, int left, int right) { + if (left >= right) return; + int mid = (left + right) >>> 1; + mergeSort(nums, indices, counts, left, mid); + mergeSort(nums, indices, counts, mid + 1, right); + merge(nums, indices, counts, left, mid, right); + } + + private void merge(int[] nums, int[] indices, int[] counts, int left, int mid, int right) { + int[] temp = new int[right - left + 1]; + int i = left, j = mid + 1, k = 0, rightCount = 0; + while (i <= mid && j <= right) { + if (nums[indices[j]] < nums[indices[i]]) { + rightCount++; + temp[k++] = indices[j++]; + } else { + counts[indices[i]] += rightCount; + temp[k++] = indices[i++]; + } + } + while (i <= mid) { + counts[indices[i]] += rightCount; + temp[k++] = indices[i++]; + } + while (j <= right) temp[k++] = indices[j++]; + for (int p = 0; p < temp.length; p++) indices[left + p] = temp[p]; + } +}