Skip to content

Instantly share code, notes, and snippets.

@yokolet
Last active May 22, 2017 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/30e80818436c3d707012fde581e1509f to your computer and use it in GitHub Desktop.
Save yokolet/30e80818436c3d707012fde581e1509f to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CountOfSmallerNumbersAfterSelf {
static class TreeNode {
int val;
int count = 1;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
static int insertNode(TreeNode root, int val) {
int thisCount = 0;
while (true) {
if (val <= root.val) {
root.count++;
if (root.left == null) {
root.left = new TreeNode(val);
break;
} else {
root = root.left;
}
} else {
thisCount += root.count;
if (root.right == null) {
root.right = new TreeNode(val);
break;
} else {
root = root.right;
}
}
}
return thisCount;
}
static List<Integer> countSmaller(int[] nums) {
List<Integer> result = new ArrayList();
if (nums == null || nums.length == 0) { return result; }
int n = nums.length;
TreeNode root = new TreeNode(nums[n - 1]);
result.add(0);
for (int i = n - 2; i >= 0; i--) {
int count = insertNode(root, nums[i]);
result.add(count);
}
Collections.reverse(result);
return result;
}
public static void main(String[] args) {
int[] nums = {5, 2, 6, 1};
System.out.println(countSmaller(nums));
int[] nums2 = {5, 2, 6, 4, 1, 3};
System.out.println(countSmaller(nums2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment