Skip to content

Commit 8a30713

Browse files
committed
another solution
1 parent 259a7ab commit 8a30713

File tree

1 file changed

+78
-1
lines changed

1 file changed

+78
-1
lines changed

algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp

+78-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/
2-
// Author : Calinescu Valentin
2+
// Author : Calinescu Valentin, Hao Chen
33
// Date : 2015-12-08
44

55
/***************************************************************************************
@@ -73,3 +73,80 @@ class Solution {
7373
return sol;
7474
}
7575
};
76+
77+
78+
/***************************************************************************************
79+
* Another solution - Binary Search Tree
80+
***************************************************************************************/
81+
82+
83+
class BinarySearchTreeNode
84+
{
85+
public:
86+
int val;
87+
int less; // count of members less than val
88+
int count; // count of members equal val
89+
BinarySearchTreeNode *left, *right;
90+
BinarySearchTreeNode(int value) : val(value), less(0),count(1),left(NULL), right(NULL) {}
91+
};
92+
93+
class BinarySearchTree
94+
{
95+
private:
96+
BinarySearchTreeNode* root;
97+
public:
98+
BinarySearchTree(const int value):root(new BinarySearchTreeNode(value)){ }
99+
~BinarySearchTree() {
100+
freeTree(root);
101+
}
102+
void insert(const int value, int &numLessThan) {
103+
insert(root, value, numLessThan);
104+
}
105+
private:
106+
void freeTree(BinarySearchTreeNode* root){
107+
if (root == NULL) return;
108+
if (root->left) freeTree(root->left);
109+
if (root->right) freeTree(root->right);
110+
delete root;
111+
}
112+
113+
void insert(BinarySearchTreeNode* root, const int value, int &numLessThan) {
114+
115+
if(value < root->val) { // left
116+
root->less++;
117+
if(root->left == NULL) {
118+
root->left = new BinarySearchTreeNode(value);
119+
}else{
120+
this->insert(root->left, value, numLessThan);
121+
}
122+
} else if(value > root->val) { // right
123+
numLessThan += root->less + root->count;
124+
if(!root->right) {
125+
root->right = new BinarySearchTreeNode(value);
126+
}else{
127+
this->insert(root->right, value, numLessThan);
128+
}
129+
} else {
130+
numLessThan += root->less;
131+
root->count++;
132+
return;
133+
}
134+
}
135+
};
136+
137+
class Solution {
138+
public:
139+
vector<int> countSmaller(vector<int>& nums) {
140+
vector<int> counts(nums.size());
141+
if(nums.size() == 0) return counts;
142+
143+
BinarySearchTree tree(nums[nums.size()-1]);
144+
145+
for(int i = nums.size() - 2; i >= 0; i--) {
146+
int numLessThan = 0;
147+
tree.insert( nums[i], numLessThan);
148+
counts[i] = numLessThan;
149+
}
150+
return counts;
151+
}
152+
};

0 commit comments

Comments
 (0)