Skip to content

Commit d2e28ac

Browse files
committed
Add solution #315
1 parent 0b5d0ed commit d2e28ac

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@
242242
303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy|
243243
306|[Additive Number](./0306-additive-number.js)|Medium|
244244
309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium|
245+
315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard|
245246
316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium|
246247
318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium|
247248
319|[Bulb Switcher](./0319-bulb-switcher.js)|Medium|
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 315. Count of Smaller Numbers After Self
3+
* https://leetcode.com/problems/count-of-smaller-numbers-after-self/
4+
* Difficulty: Hard
5+
*
6+
* Given an integer array nums, return an integer array counts where counts[i] is the
7+
* number of smaller elements to the right of nums[i].
8+
*/
9+
10+
/**
11+
* @param {number[]} nums
12+
* @return {number[]}
13+
*/
14+
var countSmaller = function(nums) {
15+
const result = new Array(nums.length).fill(0);
16+
const rank = new Map([...nums].sort((a, b) => a - b).map((n, i) => [n, i]));
17+
const group = new Array(nums.length + 1).fill(0);
18+
19+
for (let i = nums.length - 1; i >= 0; i--) {
20+
const rankIndex = rank.get(nums[i]) + 1;
21+
for (let j = rankIndex - 1, sum = 0; j > 0; j -= j & -j) {
22+
sum += group[j];
23+
result[i] = sum;
24+
}
25+
for (let j = rankIndex; j < group.length; j += j & -j) {
26+
group[j]++;
27+
}
28+
}
29+
30+
return result;
31+
};

0 commit comments

Comments
 (0)