## leetcode_ How many numbers are less than the current number

leetcode_ leetcode numbers current number

Catalog

One 、 Topic content

Two 、 Their thinking

3、 ... and 、 Code

# One 、 Topic content

Give you an array  nums, For each of these elements  nums[i], Please count all the numbers smaller than it in the array .

In other words , For each  nums[i]  You have to work out the effective  j  The number of , among j Satisfy  j != i And nums[j] < nums[i] .

Return the answer as an array .

Example 1：

Input ：nums = [8,1,2,2,3]
Output ：[4,0,1,1,3]
explain ：
about nums[0]=8 There are four smaller numbers ：（1,2,2 and 3）.
about nums[1]=1 There is no smaller number .
about nums[2]=2 There is a number smaller than it ：（1）.
about nums[3]=2 There is a number smaller than it ：（1）.
about nums[4]=3 There are three smaller numbers ：（1,2 and 2）.

Example 2：

Input ：nums = [6,5,4,8]
Output ：[2,1,0,3]

Example 3：

Input ：nums = [7,7,7,7]
Output ：[0,0,0,0]

Tips ：

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

# Two 、 Their thinking

Use a dictionary to store nums The frequency of the elements in , Then add up the frequency less than each element .

# 3、 ... and 、 Code

``````class Solution:
def smallerNumbersThanCurrent(self, nums: list) -> list:
nums_dict = {}
res = []
for i in range(101):
nums_dict[i] = 0
for num in nums:
nums_dict[num] += 1
res.append(0)
k = 0
for num in nums:
for k_num, v in nums_dict.items():
if k_num < num:
res[k] += v
else:
break
k += 1
return res
if __name__ == '__main__':
nums = [8, 1, 2, 2, 3]
s = Solution()
ans = s.smallerNumbersThanCurrent(nums)
print(ans)
``````