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]
.
题意很明确:给出一个整形数组,找出每个数字右边比它小的数字的个数。因为涉及到比大小,考虑用二叉排序树实现。难点在于二叉排序树的节点的数据结构的设计,同时要理解当一个节点插入树的时候,插入左边和右边时的对其他节点的改变策略,以及该节点的nums值的求法。另外自己要理解树的建立过程,这个题能想出算法但是却不会用代码建树实在不应该。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args){
int[] nums = new int[]{2,-1,-1};
List<Integer> a = countSmaller(nums);
for(int x : a){
System.out.print(x+" ");
}
}
public static List<Integer> countSmaller(int[] nums) {
Integer[] array = new Integer[nums.length];
Node root = null;
for(int i=nums.length-1;i>=0;i--){
root = insert(root,nums[i],array,i,0);
}
return Arrays.asList(array);
}
public static Node insert(Node root, int value, Integer[]array,int index,int leftnumber){
if(root==null){
array[index]=leftnumber;
root = new Node(value);
}
else if(value>root.value){
root.right=insert(root.right, value, array, index, leftnumber+1+root.leftnumber);
}
else{
root.leftnumber++;
root.left=insert(root.left, value, array, index, leftnumber);
}
return root;
}
}
class Node{
Node left;
Node right;
int value;
int leftnumber=0;
public Node(int value){
this.value=value;
this.left=null;
this.right=null;
}
}