题目描述
给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。
换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。
以数组形式返回答案
提示:
- 2 <= nums.length <= 500
- 0 <= nums[i] <= 100
题解
1、利用hashmap
时间复杂度:O(nlogn),空间复杂度:O(n)
- 将数组复制一份,然后排序
- 此时排序好的数组,下标为多少,就有多少个数
小于等于
它 - 需要注意的是:当数字重复的时候,第一个数的下标,就是有几个数字
小于
它
如:[1,2,2,8]为排序好的数组,此时数组中有两个2,那么第一个2的下标1,才是值小于它的个数 - 利用map记录每个数字的下标,然后给结果复制时从map之中获取,详细见代码注释
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
//tmp复制数组,res保存结果,可以合并为一个
int[] tmp = new int[nums.length];
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++){
tmp[i] = nums[i];
}
//排序tmp
Arrays.sort(tmp);
//统计每个数第一次出现的下标,即有多少个数比它小
for (int i = 0; i < tmp.length; i++){
if (!map.containsKey(tmp[i])){
map.put(tmp[i], i);
}
}
//从map中读取结果
for (int i = 0; i < tmp.length; i++){
res[i] = map.get(nums[i]);
}
return res;
}
}
2、统计计数
时间复杂度O(n),空间复杂度O(1)
- 因为
0 <= nums[i] <= 100
,所以创建数组count
,来统计每个数字出现的个数。 - 从前向后执行
count[i] += count[i - 1]
,执行之后count所代表的含义就是,nums数组中小于等于
count下标的数的个数,如:count[2] = 3, 即nums数组中小于等于
2的数字个数为3个。 - 我们要统计nums中
小于
当前数字的个数,即count[当前数字 - 1]
,详见代码注释
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] res = new int[nums.length];
//创建count数组
int[] count = new int[101];
//统计nums中每个数字出现的次数
for (int num : nums){
count[num]++;
}
//统计nums中 小于等于 当前下标数字的个数
for (int i = 1; i <= 100; i++){
count[i] += count[i - 1];
}
//找结果,注意判断,当nums[i] == 0的时候,res[i]就等于0
for (int i = 0; i < res.length; i++){
if (nums[i] - 1 >= 0) res[i] = count[nums[i] - 1];
}
return res;
}
}