leetcode 1365. 有多少小于当前数字的数字 做题笔记

题目:

给你一个数组 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)。
示例 2:

输入:nums = [6,5,4,8]
输出:[2,1,0,3]
示例 3:

输入:nums = [7,7,7,7]
输出:[0,0,0,0]

提示:

2 <= nums.length <= 500
0 <= nums[i] <= 100

思路与算法:

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

时间复杂度:O(N + K)O(N+K),其中 KK 为值域大小。需要遍历两次原数组,同时遍历一次频次数组 cntcnt 找出前缀和。

空间复杂度:O(K)O(K)。因为要额外开辟一个值域大小的数组。

代码:

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        int[] cnt = new int[101];
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            cnt[nums[i]]++;
        }
        for (int i = 1; i <= 100; i++) {
            cnt[i] += cnt[i - 1];
        }
        int[] ret = new int[n];
        for (int i = 0; i < n; i++) {
            ret[i] = nums[i] == 0 ? 0 : cnt[nums[i] - 1];
        }
        return ret;
    }
}
原文地址:https://www.cnblogs.com/nmydt/p/14256388.html