leetcode1365:有多少小于当前数字的数字

题目:

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

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

以数组形式返回答案。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

提示:

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

思路:

本题可使用桶思想,创建一个长度为101,角标从0到100的数组,将数组初始化值为0,统计每个角标在nums中出现的次数,最后统计小于nums[i]的角标出现的次数和。

代码:

class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        tmp = [0]*101

        for n in nums:
            tmp[n] += 1

        return [sum(tmp[0:n]) for n in nums]

 

posted @ 2020-06-24 09:22  how333  阅读(112)  评论(0编辑  收藏  举报