315. 计算右侧小于当前元素的个数
作者:互联网
给你一个整数数组 nums ,按要求返回一个新数组 counts 。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-of-smaller-numbers-after-self
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
private int[] ans;
/**
* 当前 i 位置的数原来在 index[i]
*/
private int[] index;
private int[] helper;
private int[] indexHelper;
private void mergeSort(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, p = l;
while (p1 <= mid && p2 <= r) {
if (nums[p1] <= nums[p2]) {
indexHelper[p] = index[p2];
helper[p++] = nums[p2++];
} else {
ans[index[p1]] += (r - p2 + 1);
indexHelper[p] = index[p1];
helper[p++] = nums[p1++];
}
}
while (p1 <= mid) {
indexHelper[p] = index[p1];
helper[p++] = nums[p1++];
}
while (p2 <= r) {
indexHelper[p] = index[p2];
helper[p++] = nums[p2++];
}
for (int i = l; i <= r; ++i) {
index[i] = indexHelper[i];
}
System.arraycopy(helper, l, nums, l, r - l + 1);
}
public List<Integer> countSmaller(int[] nums) {
if (nums == null || nums.length == 0) {
return Collections.emptyList();
}
this.ans = new int[nums.length];
this.index = new int[nums.length];
this.helper = new int[nums.length];
this.indexHelper = new int[nums.length];
for (int i = 0; i < nums.length; ++i) {
index[i] = i;
}
int[] copy = new int[nums.length];
System.arraycopy(nums, 0, copy, 0, nums.length);
mergeSort(copy, 0, nums.length - 1);
List<Integer> ret = new ArrayList<>(ans.length);
for (int i = 0; i < ans.length; ++i) {
ret.add(ans[i]);
}
return ret;
}
}
标签:nums,int,个数,315,length,private,ans,new,右侧 来源: https://www.cnblogs.com/tianyiya/p/15662663.html