赞
踩
- class Solution {
- public:
- vector<int> countSmaller(vector<int>& nums) {
- vector<pair<int, int>> array(nums.size());
- count.resize(nums.size(), 0);
- for(int i=0; i<nums.size(); i++){
- array[i] = {i, nums[i]};
- }
- tmp.resize(nums.size());
- sort(array, 0, nums.size()-1);
- return count;
- }
- vector<pair<int, int>> tmp;
- vector<int> count;
- void sort(vector<pair<int, int>>& array, int lo, int hi){
- if(lo >= hi) return;
- int mid = (lo + hi) >> 1;
- sort(array, lo, mid);
- sort(array, mid+1, hi);
- merge(array, lo, mid, hi);
- }
- void merge(vector<pair<int, int>>& array, int lo, int mid, int hi){
- for(int i=lo; i<=hi; i++){
- tmp[i] = array[i];
- }
- int i = lo;
- int j = mid+1;
- for(int p=lo; p<=hi; p++){
- if(i == mid+1){
- array[p] = tmp[j++];
- }
- else if(j == hi+1){
- array[p] = tmp[i++];
- count[array[p].first] += j-mid-1;
- }
- else if(tmp[i].second > tmp[j].second){
- array[p] = tmp[j++];
- }
- else if(tmp[i].second <= tmp[j].second){
- array[p] = tmp[i++];
- count[array[p].first] += j-mid-1;
- }
- }
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。