LeetCode 1365. 有多少小于当前数字的数字 java题解
https://leetcode.cn/problems/how-many-numbers-are-smaller-than-the-current-number/description/
对于排序后的数组,它的下标就代表了前面有多少<=它的数。
可以用一个哈希表来记录数字,和小于它的数字数量。
而题目需要的是小于它的数的数量,原数组中的数字有重复情况。也就是说,前面如果有等于它的数,是不算入结果的。解决方法是倒序遍历排序数组,从后往前加入哈希表,这样同样的数,前面的结果更小,哈希表会用前面的结果覆盖后面的结果。
class Solution {public int[] smallerNumbersThanCurrent(int[] nums) {int len=nums.length;int[] sort_nums=new int[len];for(int i=0;i<len;i++) sort_nums[i]=nums[i];Arrays.sort(sort_nums);HashMap<Integer,Integer> map=new HashMap<>();//num,原indexfor(int i=len-1;i>=0;i--){//倒序遍历排序后数组,数组下标就代表他前面有几个map.put(sort_nums[i],i);}int[] res=new int[len];for(int i=0;i<len;i++){res[i]=map.get(nums[i]);}return res;}
}