-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution315.cs
45 lines (39 loc) · 1.03 KB
/
Solution315.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
namespace LeetCode.Solutions;
public class Solution315
{
/// <summary>
/// 315. Count of Smaller Numbers After Self - Hard
/// <a href="https://leetcode.com/problems/count-of-smaller-numbers-after-self">See the problem</a>
/// </summary>
public IList<int> CountSmaller(int[] nums)
{
var n = nums.Length;
var result = new int[n];
var sorted = new List<int>();
for (var i = n - 1; i >= 0; i--)
{
var index = BinarySearch(sorted, nums[i]);
result[i] = index;
sorted.Insert(index, nums[i]);
}
return result;
}
private int BinarySearch(List<int> sorted, int target)
{
var left = 0;
var right = sorted.Count;
while (left < right)
{
var mid = left + (right - left) / 2;
if (sorted[mid] < target)
{
left = mid + 1;
}
else
{
right = mid;
}
}
return left;
}
}