-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountofSmallerNumbersAfterSelf.java
83 lines (75 loc) · 2.32 KB
/
CountofSmallerNumbersAfterSelf.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Example:
Given nums = [5, 2, 6, 1]
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.
Return the array [2, 1, 1, 0].
*/
import java.util.*;
public class CountofSmallerNumbersAfterSelf {
public static class TreeNode{
TreeNode left;
TreeNode right;
int val;
int count;
public TreeNode(int val){
this.val = val;
this.count = 1;
}
}
public static List<Integer> countSmaller(int[] nums) {
List<Integer> res = new ArrayList<>();
if(nums.length <= 0) return res;
int L = nums.length;
res.add(0);
TreeNode root = new TreeNode(nums[L-1]);
for(int i = L-2; i >= 0; i--){
int count = findCount(root, nums[i]);
res.add(count);
}
Collections.reverse(res);
return res;
}
public static int findCount(TreeNode node, int num){
int acount = 0;
while(true){
if(node.val < num){
acount += node.count;
if(node.right == null){
TreeNode r = new TreeNode(num);
node.right = r;
break;
}else{
node = node.right;
}
}else{
node.count++;
if(node.left == null){
TreeNode l = new TreeNode(num);
node.left = l;
break;
}else{
node = node.left;
}
}
}
return acount;
}
public static void main(String[] args) {
int[] nums1 = new int[] {12, 2, 27, 8, 35, 56, 2, 2, 3};
System.out.println("Array: ");
for(int i=0; i < nums1.length; i++){
System.out.print(nums1[i] + " ");
}
System.out.println();
System.out.println("Res: ");
List<Integer> nums2 = countSmaller(nums1);
for(int i=0; i < nums2.size(); i++){
System.out.print(nums2.get(i) + " ");
}
return;
}
}