题目:
给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。
换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。
以数组形式返回答案。
示例 1:
输入:nums = [8,1,2,2,3]
输出:[4,0,1,1,3]
解释:
对于 nums[0]=8 存在四个比它小的数字:(1,2,2 和 3)。
对于 nums[1]=1 不存在比它小的数字。
对于 nums[2]=2 存在一个比它小的数字:(1)。
对于 nums[3]=2 存在一个比它小的数字:(1)。
对于 nums[4]=3 存在三个比它小的数字:(1,2 和 2)。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/how-many-numbers-are-smaller-than-the-current-number
思路:
数组中排序,并且按照下标的顺序进行输出!
需要联想到需要记录下标和数值的映射关系,就要用到哈希表!本题中可以用数组当哈希表,也可使使用Map;
原来的数组不能动,原来的数组需要确定位置关系;
新的拷贝数组排序,可以记录大小数量关系!数值和其大小数量关系,记录在哈希表中;
遍历时,每次到哈希中找结果!
Map中相同的数字只记录一次,后续的数量不更新
★计数排序:
当排序的数值数量有限时,可以用数组一一表示!
代码:
1)暴力:时间复杂度O(N^2)
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
//暴力:
int len = nums.length;
int[] res = new int[len];
for(int i = 0;i < len;i++){
int num = 0;
for(int j = 0;j < len;j++){
if(nums[j] < nums[i]) num++;
}
res[i] = num;
}
return res;
}
}
2)哈希表:记录数字和下标的映射关系,再进行排序
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
//记录下标并且排序:用map
HashMap<Integer,Integer> map = new HashMap<>();
int[] res = Arrays.copyOf(nums,nums.length);
Arrays.sort(res);//从大到小排序
for(int i = 0;i < nums.length;i++){
if(!map.containsKey(res[i])){
map.put(res[i],i);
}
}
for(int i = 0;i < nums.length;i++){
res[i] = map.get(nums[i]);
}
return res;
}
}
3)计数排序:数组中只记录频数
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
//计数排序,数值的个数是有限的
int[] nums101 = new int[101];
int[] res = new int[nums.length];
for(int i = 0;i < nums.length;i++){
nums101[nums[i]]++;//统计数字出现的次数!数字从0 - 100
}
//某个数字之前的数字出现的次数,就是比它小的数字的综合
for(int i = 1;i < nums101.length;i++){
nums101[i] = nums101[i - 1] + nums101[i];//小于等于当前值的 数字的频数!就是当前数值数量 + 小于他的数量
}
for(int i = 0;i < nums.length;i++){
if(nums[i] > 0)//保证不会出现负数;等于0时,结果肯定为0
res[i] = nums101[nums[i] - 1];
}
return res;
}
}