Skip to content

Commit ace2fb9

Browse files
authored
Update 315-count-of-smaller-numbers-after-self.js
1 parent 3237219 commit ace2fb9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

315-count-of-smaller-numbers-after-self.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,46 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
const countSmaller = function(nums) {
6+
const numsAndIndexes = nums.map((x, i) => [x, i])
7+
const output = [...new Array(nums.length)].map(_ => 0)
8+
mergeSort(numsAndIndexes, output)
9+
return output
10+
}
11+
12+
function mergeSort(arr, output) {
13+
if (arr.length <= 1) return arr
14+
const middle = Math.floor(arr.length / 2)
15+
const left = mergeSort(arr.slice(0, middle), output),
16+
right = mergeSort(arr.slice(middle), output)
17+
const sorted = []
18+
let i = 0,
19+
j = 0
20+
while (i < left.length || j < right.length) {
21+
if (i >= left.length) {
22+
sorted.push(right[j])
23+
j++
24+
} else if (j >= right.length) {
25+
sorted.push(left[i])
26+
i++
27+
} else {
28+
if (left[i][0] > right[j][0]) {
29+
sorted.push(left[i])
30+
output[left[i][1]] += right.length - j
31+
i++
32+
} else {
33+
sorted.push(right[j])
34+
j++
35+
}
36+
}
37+
}
38+
39+
return sorted
40+
}
41+
42+
// another
43+
144
class Node {
245
constructor(v, s) {
346
this.val = v

0 commit comments

Comments
 (0)