File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ from typing import List
2+
3+
4+ class Solution :
5+ def countSmaller (self , nums : List [int ]) -> List [int ]:
6+
7+ n = len (nums )
8+ counts = [0 ] * n
9+
10+ # (값, 원래 index)
11+ arr = [(nums [i ], i ) for i in range (n )]
12+
13+ def merge_sort (left , right ):
14+
15+ if left >= right :
16+ return
17+
18+ mid = (left + right ) // 2
19+
20+ merge_sort (left , mid )
21+ merge_sort (mid + 1 , right )
22+
23+ temp = []
24+
25+ i = left
26+ j = mid + 1
27+
28+ # 오른쪽에서 이미 가져온 작은 원소 개수
29+ right_smaller = 0
30+
31+ while i <= mid and j <= right :
32+
33+ if arr [j ][0 ] < arr [i ][0 ]:
34+ temp .append (arr [j ])
35+ right_smaller += 1
36+ j += 1
37+
38+ else :
39+ # arr[i]보다 작은 오른쪽 원소들의 개수
40+ counts [arr [i ][1 ]] += right_smaller
41+
42+ temp .append (arr [i ])
43+ i += 1
44+
45+ # 왼쪽에 남은 원소
46+ while i <= mid :
47+ counts [arr [i ][1 ]] += right_smaller
48+
49+ temp .append (arr [i ])
50+ i += 1
51+
52+ # 오른쪽에 남은 원소
53+ while j <= right :
54+ temp .append (arr [j ])
55+ j += 1
56+
57+ # 정렬된 결과를 원래 배열에 반영
58+ arr [left :right + 1 ] = temp
59+
60+ merge_sort (0 , n - 1 )
61+
62+ return counts
You can’t perform that action at this time.
0 commit comments