Leetcode 315: Count of Smaller Numbers After Self

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].

 

 

 
 1 public class Solution {
 2     public class TreeNode
 3     {
 4         public int val;
 5         public int smaller;
 6         public int dup;
 7         public TreeNode left;
 8         public TreeNode right;
 9         
10         public TreeNode(int val, int smaller)
11         {
12             this.val = val;
13             this.smaller = smaller;
14             this.dup = 1;
15         }
16     }
17     
18     public IList<int> CountSmaller(int[] nums) {
19         TreeNode root = null;
20         var result = new int[nums.Length];
21         
22         for (int i = nums.Length - 1; i >= 0; i--)
23         {
24             root = InsertNode(result, i, nums[i], 0, root);
25         }
26         
27         return result.ToList();
28     }
29     
30     private TreeNode InsertNode(int[] result, int index, int val, int preSmaller, TreeNode node) 
31     {
32         if (node == null)
33         {
34             node = new TreeNode(val, 0);
35             result[index] = preSmaller;
36         }
37         else if (val == node.val)
38         {
39             node.dup++;
40             result[index] = node.smaller + preSmaller;
41         }
42         else if (val < node.val)
43         {
44             node.smaller++;
45             node.left = InsertNode(result, index, val, preSmaller, node.left);
46         }
47         else
48         {
49             node.right = InsertNode(result, index, val, preSmaller + node.smaller + node.dup, node.right);
50         }
51         
52         
53         return node;
54     }
55 }

 

posted @ 2017-12-09 06:59  逸朵  阅读(114)  评论(0)    收藏  举报