-
Notifications
You must be signed in to change notification settings - Fork 85
/
Count of Smaller Numbers After Self.java
63 lines (57 loc) · 1.52 KB
/
Count of Smaller Numbers After Self.java
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
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;
}
}