vector<int> countSmaller(vector<int>& nums) {
     vector<int> result(nums.size(), 0);
     bit.resize(nums.size()+1, 0);
     
     //get the ordered-index-array
     vector<int> sorted_nums(nums);
     vector<int> places(nums.size(), 0);
     sort(sorted_nums.begin(), sorted_nums.end());
     for (int i = 0; i < nums.size(); ++i) {
         places[i] = lower_bound(sorted_nums.begin(), sorted_nums.end(), nums[i]) - sorted_nums.begin();
         //cout<<i<<"th places:"<<places[i]<<endl;
     }
     
     for(int i=places.size()-1; i>=0; i--){
         result[i]=bit_sum(places[i]-1);
         bit_add(places[i], 1);
     }
     
     return result;
 }
Example #2
0
void merge(vector<int> & nums, int begin, int mid, int end){
	vector<int> sorted_nums(end-begin+1);
	int cur_pos = 0;

	int left = begin;
	int right = mid +1;
	while( left <= mid && right <= end){
		if( nums[left] < nums[right] ){
			sorted_nums[cur_pos ++ ] = nums[left ++];
		}else{
			sorted_nums[cur_pos ++ ] = nums[right ++];
		}
	}
	while( left <= mid){
		sorted_nums[cur_pos ++] = nums[left ++];
	}
	while( right <= end){	
		sorted_nums[cur_pos ++] = nums[right ++];
	}
	for(int i=0; i < cur_pos; i ++ ){
		nums[begin +i] = sorted_nums[i];
	}
}