Count of Smaller Numbers After Self

首先吐槽下CSDN,写完,发表,直接没了,辛苦写的东西就这么不见了……

You are given an integer array nums and you have to return a new counts array. Thecounts 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,输出数组arr,其中arr[i]的值是数组nums中位于nums[i]右侧且小于nums[i]的元素是数目,如果暴力搜索的话,时间复杂度大概为O(n^2),太高了。题目是比较位于右侧的元素,因此我们逆序遍历数组nums,并把大小信息用二叉查找树存储起来。在构造二叉查找树的时候,为每个二叉查找树节点增加一个属性用于记录子树节点数目,便于后续统计符合要求的元素数目。同时,需要考虑数组中值相同的元素,由于统计的是小于目标的元素数目,因此把相等的值也插入节点的右子树中。代码如下:

	class BinarySearchTreeNode{
		BinarySearchTreeNode leftChildren;
		BinarySearchTreeNode rightChildren;
		int value;
		int num;
		public BinarySearchTreeNode(int v){
			this.value = v;
			num = 1;
		}
	}
	public int insert(int v, BinarySearchTreeNode node){
		int re = 0;
		while(true){
			if(v < node.value){
				node.num ++;
				if(node.leftChildren == null){
					node.leftChildren = new BinarySearchTreeNode(v);
					break;
				}
				node = node.leftChildren;
			}
			else{
				node.num ++;
				// v >= node.value,加上左子树以及node本身
				re += getNum(node.leftChildren);
				if(node.value != v)
					re++;
				if(node.rightChildren == null){
					node.rightChildren = new BinarySearchTreeNode(v);
					break;
				}
				node = node.rightChildren;
			}
		}
		
		return re;
	}
	
	private int getNum(BinarySearchTreeNode node){
		if(node == null)
			return 0;
		else
			return node.num;
	}
	
	public List<Integer> countSmaller(int[] nums) {
        	LinkedList<Integer> reList = new LinkedList<Integer>();
        	if(nums == null || nums.length == 0)
        		return reList;
        	reList.addFirst(0);
        	BinarySearchTreeNode root = new BinarySearchTreeNode(nums[nums.length-1]);
        	for(int i=nums.length-2; i >= 0; i--){
        		int el = nums[i];
        		int re = insert(el,root);
        		reList.addFirst(re);
        	}
        
        	return reList;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值