**给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-of-smaller-numbers-after-self
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。**
示例
输入:nums = [5,2,6,1]
输出:[2,1,1,0]
解释:
5 的右侧有 2 个更小的元素 (2 和 1)
2 的右侧仅有 1 个更小的元素 (1)
6 的右侧有 1 个更小的元素 (1)
1 的右侧有 0 个更小的元素
Java归并加索引
时间复杂度 O(N*lgN)
class Solution {
public static class Node{
int value;
int i;
}
public static List<Integer> countSmaller(int[] nums){
List<Integer> list = new ArrayList<Integer>();
Node[] nodes = new Node[nums.length];
for(int i=0;i<nums.length;i++){
Node nn= new Node();
nodes[i] = nn;
nodes[i].value = nums[i];
nodes[i].i = i;
}
int[] result = new int[nums.length];
process(result,0,nums.length-1,nodes);
for(int i=0;i<result.length;i++){
list.add(result[i]);
}
return list;
}
public static void process(int[] arr,int left,int right,Node[]res){
if(left>=right){
return;
}
int mid=left+((right-left)>>1);
process(arr,left,mid,res);
process(arr,mid+1,right,res);
merge(arr,left,mid,right,res);
}
public static void merge(int[] res,int L,int M,int R,Node[]node){
int p1=L;
int p2=M+1;
int index=0;
Node []help=new Node[R-L+1];
while(p1<=M&&p2<=R){
res[node[p1].i]+=node[p1].value<=node[p2].value?p2-M-1:0;
help[index++]=node[p1].value<=node[p2].value?node[p1++]:node[p2++];
}
while(p1<=M){
res[node[p1].i]+=R-M;
help[index++]=node[p1++];
}
while(p2<=R){
help[index++]=node[p2++];
}
for (int j = 0; j < help.length; j++) {
node[L+j]=help[j];
}
}
public static void main(String[] args){
int [] arr={2,0,1};
countSmaller(arr);
}
}
c++实现
class Solution {
public:
vector<int> res;
vector<pair<int,int>> temp;
vector<pair<int,int>> pairIdx;
void mergeSort (vector<pair<int,int>>& nums,int l,int r){
if(l >= r) return;
int mid = (l + r) >> 1;
mergeSort(nums,l,mid);
mergeSort(nums,mid+1,r);
int p1=l,p2=mid+1,k=0;
while(p1 <= mid && p2 <= r){
if(nums[p1].first <= nums[p2].first){
res[nums[p1].second] += p2-mid-1;
temp[k++] = nums[p1++];
}
else temp[k++] = nums[p2++];
}
while(p1 <= mid){
res[nums[p1].second] += p2-mid-1;
temp[k++] = nums[p1++];
}
while(p2 <= r) temp[k++] = nums[p2++];
for(int i = l,j=0;i <= r;i++,j++) nums[i] = temp[j];
}
vector<int> countSmaller(vector<int>& nums) {
res = vector<int>(nums.size(),0);
temp = vector<pair<int,int>>(nums.size());
for(int i = 0; i < nums.size(); ++i) pairIdx.push_back({nums[i],i});
mergeSort(pairIdx,0,nums.size()-1);
return res;
}
};