[leetCode]1365. 有多少小于当前数字的数字

csdn:https://blog.csdn.net/renweiyi1487/article/details/109296906

题目

链接:https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number

给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。

换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != inums[j] < nums[i]

以数组形式返回答案。

示例:

输入: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)。

快速排序 + 哈希

通过观察可知讲数组排序后数组中元素的下标即为在该数组中有几个元素小于当前元素。所以需要建立该元素与其下标的映射,通过原数组进行查询即可得到结果。需要注意的是数组中存在重复的元素,因此不能重复添加相同的元素。

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        int n = nums.length;
        int[] copy = Arrays.copyOf(nums, n);
        Arrays.sort(copy);
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            if (!map.containsKey(copy[i]))
                map.put(copy[i], i);
        }
        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            ans[i] = map.get(nums[i]);
        }
        return ans;
    }
}

快速排序 + 数组

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        int n = nums.length;
        // 定义一个数组用来保存数组元素与其在数组中的位置
        int[][] data = new int[n][2];
        for (int i = 0; i < n; i++) {
            data[i][0] = nums[i];
            data[i][1] = i 
        }
        // 自定义对象数组排序
        Arrays.sort(data, new Comparator<int[]>() {
            public int compare(int[] data1, int[] data2) {
                return data1[0] - data2[0];
            }
        });
        int[] ans = new int[n];
        // 记录排序后前一个元素的下标值
        int prev = -1;
        for (int i = 0; i < n; i++) {
            if (i == 0 || data[i][0] != data[i - 1][0]) {
                prev = i;
            }
            ans[data[i][1]] = prev;
        }
        return ans;
    }
}

计数排序

注意到数组元素的值域为 [0,100],所以可以考虑建立一个频次数组 cntcnt[i] 表示数字 i 出现的次数。那么对于数字 i 而言,小于它的数目就为 cnt[0...i−1] 的总和。

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        int[] cnt = new int[101];
        int n = nums.length;
        // 记录每个元素(作为下标)出现的次数
        for (Integer num : nums) {
            cnt[num] ++;
        }
        for (int i = 1; i < 101; i++) {
            cnt[i] += cnt[i - 1];
        }
        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            ans[i] = nums[i] == 0 ? 0 : cnt[nums[i] - 1];
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13881055.html