another solution

This commit is contained in:
Hao Chen 2016-01-15 15:03:32 +08:00
parent 259a7abf7e
commit 8a3071370f

View File

@ -1,5 +1,5 @@
// Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/
// Author : Calinescu Valentin
// Author : Calinescu Valentin, Hao Chen
// Date : 2015-12-08
/***************************************************************************************
@ -73,3 +73,80 @@ public:
return sol;
}
};
/***************************************************************************************
* Another solution - Binary Search Tree
***************************************************************************************/
class BinarySearchTreeNode
{
public:
int val;
int less; // count of members less than val
int count; // count of members equal val
BinarySearchTreeNode *left, *right;
BinarySearchTreeNode(int value) : val(value), less(0),count(1),left(NULL), right(NULL) {}
};
class BinarySearchTree
{
private:
BinarySearchTreeNode* root;
public:
BinarySearchTree(const int value):root(new BinarySearchTreeNode(value)){ }
~BinarySearchTree() {
freeTree(root);
}
void insert(const int value, int &numLessThan) {
insert(root, value, numLessThan);
}
private:
void freeTree(BinarySearchTreeNode* root){
if (root == NULL) return;
if (root->left) freeTree(root->left);
if (root->right) freeTree(root->right);
delete root;
}
void insert(BinarySearchTreeNode* root, const int value, int &numLessThan) {
if(value < root->val) { // left
root->less++;
if(root->left == NULL) {
root->left = new BinarySearchTreeNode(value);
}else{
this->insert(root->left, value, numLessThan);
}
} else if(value > root->val) { // right
numLessThan += root->less + root->count;
if(!root->right) {
root->right = new BinarySearchTreeNode(value);
}else{
this->insert(root->right, value, numLessThan);
}
} else {
numLessThan += root->less;
root->count++;
return;
}
}
};
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
vector<int> counts(nums.size());
if(nums.size() == 0) return counts;
BinarySearchTree tree(nums[nums.size()-1]);
for(int i = nums.size() - 2; i >= 0; i--) {
int numLessThan = 0;
tree.insert( nums[i], numLessThan);
counts[i] = numLessThan;
}
return counts;
}
};