【发布时间】:2020-05-15 21:37:13
【问题描述】:
我正在处理 leetcode 问题编号 1365。以下是斜体字符:
给定数组 nums,对于每个 nums[i] 找出数组中有多少个数小于它。也就是说,对于每个 nums[i],您必须计算有效 j 的数量,使得 j != i 并且 nums[j]
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
我能够使用蛮力完成任务,这给了 O(n^2) 时间。有没有更快的方法来解决这个问题?
public static void main(String[] args) {
int[] nums = new int[] {8,1,2,2,3};
System.out.println(Arrays.toString(smallerNumbersThanCurrent(nums)));
}
public static int[] smallerNumbersThanCurrent(int[] nums) {
int[] result = new int[nums.length];
for (int x = 0; x < nums.length; x++) {
int ctr = 0;
for (int y = 0; y < nums.length; y++) {
if (nums[y] < nums[x]) {
ctr++;
}
result[x] = ctr;
}
}
return result;
}
【问题讨论】: