315、Count of Smaller Numbers After Self(Hard)

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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值