https://leetcode.com/problems/count-of-smaller-numbers-after-self/
You were given an integer array nums and you had to return a new counts array. The counts array has the property where are the number of smaller elements to the right of counts[i]
nums[i]
.
Example:
Nums 2 1 1 0 smaller element.
Return the array [2, 1, 1, 0]
.
classSolution {classtreenode{ Public:intVal, rank; TreeNode*l, *S; TreeNode (intV): Val (v), rank (1), L (null), R (null) {}}; Public: intGetRank (treenode* root,intv) {intRank =0; while(true) { if(v <= root->val) { ++root->rank; if(Root->l = =NULL) {Root->l =NewTreeNode (v); Break; } Elseroot = root->l; } Else{Rank+ = Root->rank; if(Root->r = =NULL) {Root->r =NewTreeNode (v); Break; } Elseroot = root->R; } } returnrank; } Vector<int> Countsmaller (vector<int>&nums) {Vector<int>Res; if(nums.size () = =0)returnRes; TreeNode* Root =NewTreeNode (Nums[nums.size ()-1]); Res.push_back (0); for(intI=nums.size ()-2; i>=0; --i) {intRank =GetRank (Root, nums[i]); Res.push_back (rank); } Vector<int>Rev_res; for(vector<int>::reverse_iterator p = res.rbegin (); P!=res.rend (); ++P) Rev_res.push_back (*p); returnRev_res; }};
https://leetcode.com/problems/kth-largest-element-in-an-array/
Find the kth largest element in an unsorted array. Note that it was the kth largest element in the sorted order and not the kth distinct element.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k are always valid, 1≤k≤array ' s length.
classSolution {classtreenode{ Public:intVal, rank; TreeNode*l, *R; TreeNode (intV): Val (v), rank (1), L (null), R (null) {}}; Public: voidAddNode (treenode* root,intv) { while(true) { if(v <= root->val) { ++root->rank; if(Root->l = =NULL) {Root->l =NewTreeNode (v); Break; } Elseroot = root->l; } Else{ if(Root->r = =NULL) {Root->r =NewTreeNode (v); Break; } Elseroot = root->R; } } } voidDFS (treenode* root,intKint&Res) { if(Root->rank = =k) {res= root->Val; return; } if(root->l) DFS (root->L, K, res); if(root->r) DFS (Root->r, k-root->rank, res); } intFindkthlargest (vector<int>& Nums,intk) {if(nums.size () = =1)returnnums[0]; TreeNode*root =NewTreeNode (nums[0]); for(intI=1; I<nums.size (); ++i) {AddNode (root, nums[i]); } intres =-1; DFS (Root, nums.size ()-K +1, RES); returnRes; }};
[email protected] [315/215] Count of Smaller Numbers after self/kth largest Element in an Array (BST)