"Leetcode" Count of Smaller Numbers after self

Source: Internet
Author: User

Title Link: https://leetcode.com/problems/count-of-smaller-numbers-after-self/

Topic:

you is given an integer array nums and that you had to return a new counts array. The counts array have the property where counts[i"  is the number of smaller elements to the right Of nums[i] .

Example:

2 1 1 0 smaller element.

Return the array [2, 1, 1, 0] .

Ideas:

Set up a binary search tree, in the process of building, recorded in the array to the right of the number of elements smaller than itself. Algorithm complexity O (NLOGN), with dynamic programming complexity of O (n^2).

Where CNT is the number of elements of the same size of the node, used for repeating element judgments ... can be omitted in fact. Too lazy to change

Algorithm:

Public list<integer> Countsmaller (int[] nums) {list<integer> List = new arraylist<integer> ();          int res[] = new Int[nums.length];          for (int i = nums.length-1; I >= 0; i--) {Res[i] = insert (nums[i]);          } for (int i:res) {list.add (i);      } return list;        } TreeNode Troot;          Private Integer Insert (int val) {int cnt = 0;              if (troot = = null) {troot = new TreeNode (val);          return CNT;          } TreeNode root = Troot;                  while (root = null) {if (Val < root.val) {root.leftcnt++;                      if (Root.left = = null) {Root.left = new TreeNode (val);                  Break              } else root = Root.left;                  } else if (val > Root.val) {cnt + = root.leftcnt + root.cnt; if (ROOT.Right = = null) {root.right = new TreeNode (val);                  Break              } else root = Root.right;                  } else {cnt + = root.leftcnt;                  root.cnt++;              Break      }} return CNT;   }


"Leetcode" Count of Smaller Numbers after self

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.