您的位置:首页 > 其它

[Leetcode]Count of Smaller Numbers After Self

2016-01-20 18:08 369 查看
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]
.

class Solution {
public:
/*algorithm: hash
time O(n*n) space O(n)
*/
vector<int> countSmaller(vector<int>& nums) {
vector<int>count(nums.size(),0);
for(int i = 0;i < nums.size();i++){
for(int j = 0;j < i;j++){
if(nums[j] > nums[i]){
count[j]++;
}
}
}
return count;
}
};
class Solution {
public:
/*algorithm: binary search tree
time O(nlgn) space O(n)
*/
struct TreeNode{
int val;
int cnt;//left child nodes count
int same; //same number nodes count
TreeNode* left,*right;
TreeNode(int v):val(v),cnt(0),same(1),left(NULL),right(NULL){}
};
int insert(TreeNode* &root,int val){
if(!root){
root = new TreeNode(val);
return 0;
}
TreeNode* t = root;
int count = 0;
while(t){
if(t->val > val){
t->cnt++;
if(!t->left){
t->left = new TreeNode(val);
break;
}
t = t->left;
}else if(t->val < val){
count += t->cnt + t->same;
if(!t->right){
t->right = new TreeNode(val);
break;
}
t = t->right;
}else{
count += t->cnt;
t->same++; //add self number occurence
break;
}
}
return count;
}
vector<int> countSmaller(vector<int>& nums) {
vector<int>count(nums.size(),0);
TreeNode* root = NULL;
for(int i = (int)nums.size()-1;i >= 0;i--){
count[i] = insert(root,nums[i]);
}
return count;
}
};


/*algorithm: merge sort
time O(nlgn)
*/
struct NumberIndex {
int number;
int index;
NumberIndex(int val, int index):number(val),index(index){}
};
vector<NumberIndex> mergeSort(vector<NumberIndex>&nums,vector<int>&smaller) {
int half = nums.size() / 2;
if (half > 0) {
vector<NumberIndex> leftPart,rightPart;
int k;
for (k = 0; k < half; k++) {
leftPart.push_back(nums[k]);
}
for (;k < nums.size();k++) {
rightPart.push_back(nums[k]);
}
vector<NumberIndex> left = mergeSort(leftPart, smaller);
vector<NumberIndex> right = mergeSort(rightPart, smaller);
int i = 0, j = 0,d = 0;
while (i <left.size() || j < right.size()) {
if (j == right.size() || i < left.size() && left[i].number <= right[j].number) {
nums[d++] = left[i];
smaller[left[i].index] += j;
i++;
} else {
nums[d++] = right[j];
j++;
}
}
}

return nums;
}

vector<int> countSmaller(vector<int>& nums) {
vector<NumberIndex>cnums;
for (int i = 0; i < nums.size(); i++) {
cnums.push_back(NumberIndex(nums[i],i));
}
vector<int>smaller(nums.size(),0);
mergeSort(cnums, smaller);
return smaller;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法