-
Notifications
You must be signed in to change notification settings - Fork 64
/
CountSmallerNumberAfterSelf.cpp
88 lines (76 loc) · 2.15 KB
/
CountSmallerNumberAfterSelf.cpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// LEETCODE 315. Count of Smaller Numbers After Self { Hard } {Array}
// Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
// Example 1:
// Input: nums = [5,2,6,1]
// Output: [2,1,1,0]
// Explanation:
// To the right of 5 there are 2 smaller elements (2 and 1).
// To the right of 2 there is only 1 smaller element (1).
// To the right of 6 there is 1 smaller element (1).
// To the right of 1 there is 0 smaller element.
// Example 2:
// Input: nums = [-1]
// Output: [0]
// Example 3:
// Input: nums = [-1,-1]
// Output: [0,0]
### Solution
```
class Solution {
public class TreeNode
{
int val;
int count = 1;
TreeNode left;
TreeNode right;
TreeNode(int val)
{
this.val = val;
}
}
public int insert_BST(TreeNode root, int val)
{
int sum = 0;
while(true)
{
if(val <= root.val)
{
root.count++;
if(root.left != null)
root = root.left;
else
{
root.left = new TreeNode(val);
break;
}
}
else
{
sum+= root.count;
if(root.right != null)
root = root.right;
else
{
root.right = new TreeNode(val);
break;
}
}
}
return sum;
}
public List<Integer> countSmaller(int[] nums) {
List<Integer> ans = new ArrayList<>();
if(nums == null || nums.length ==0)
return ans;
TreeNode root = new TreeNode(nums[nums.length-1]);
ans.add(0);
for(int i = nums.length-2; i >=0; i--)
{
int count = insert_BST(root, nums[i]);
ans.add(count);
}
Collections.reverse(ans);
return ans;
}
}
```