-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path315. Count of Smaller Numbers After Self.java
69 lines (69 loc) · 1.91 KB
/
315. 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
64
65
66
67
68
69
public static void main(String[] args) throws IOException {
FastScanner fs = new FastScanner();
int n = fs.nextInt();
int[] arr = fs.readArray(n);
List<Integer> ans = new MinimumAfterSelf().countSmaller(arr);
System.out.println(ans);
}
// Optimation Using BST / MinHeap
class Node {
Node left;
Node right;
int data;
int count;
Node(int d, Node l, Node r) {
this.data = d;
this.left = l;
this.right = r;
this.count = 1;
}
}
public List<Integer> countSmaller(int[] nums) {
/*
* Build BST and Count
*/
final int n = nums.length;
List<Integer> smallers = new ArrayList<Integer>();
if (nums == null || nums.length == 0)
return smallers;
Node root = new Node(nums[n - 1], null, null);
smallers.add(0);
for (int i = n - 2; i >= 0; i--) {
int smallerElems = construct(root, nums[i]);
smallers.add(smallerElems);
}
Collections.reverse(smallers);
return smallers;
}
private int construct(Node root, int data) {
// TODO Auto-generated method stub
int smallerNodes = 0;
while (true) {
if (data <= root.data) {
// go left
root.count++;
if (root.left == null) {
root.left = new Node(data, null, null);
break;
} else {
root = root.left;
}
} else {
// go right
smallerNodes += root.count;
if (root.right == null) {
root.right = new Node(data, null, null);
break;
} else {
root = root.right;
}
}