leetcode学习笔记19

315. Count of Smaller Numbers After Self

Input: [5,2,6,1]
Output: [2,1,1,0]
Explanation:
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.
采用二叉树的方法,从后往前遍历,结果等于父节点+父节点左边所有的子节点。
此方法的缺点为极端情况下,时间复杂度会达到O(n^n)

class Solution {
	public List<Integer> countSmaller(int[] nums) {
		LinkedList<Integer> res = new LinkedList<Integer>();
		if (nums.length == 0)
			return res;
		TreeNode root = new TreeNode(nums.length - 1);
		res.addFirst(0);
		for (int i = nums.length - 2; i >= 0; i--) {
			int count = 0;
			TreeNode node = new TreeNode(i);
			TreeNode cmp = root;
			while (true) {
				if (nums[i] > nums[cmp.val]) {
					count += cmp.leftNum +1;
					if (cmp.right == null) {
						cmp.right = node;
						break;
					} else
						cmp = cmp.right;
				} else {
					cmp.leftNum++;
					if (cmp.left == null) {
						cmp.left = node;
						break;
					} else
						cmp = cmp.left;
				}	
			}
			res.addFirst(count);
		}
		return res;
	}

	class TreeNode {
		int val, leftNum;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
			leftNum = 0;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_38941866/article/details/84994914