leetcode--python--1365

1365. How many numbers are less than the current number

Give you an array nums, for each element nums[i], please count the number of all numbers smaller than it in the array.

In other words, for each nums[i] you must calculate the number of valid j, where j satisfies j != i and nums[j] <nums[i].

Return the answer as an array
Limit: 2 <= nums.length <= 500; 0 <= nums[i] <= 100

class Solution(object):
    def smallerNumbersThanCurrent(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        result = []
        nums_less = []
        n = 0
        nums_tem = [0] * 101
        for i in nums:
            nums_tem[i] += 1
        for j in nums_tem:
            nums_less.append(n)
            n += nums_tem[j]
        for k in nums:
            result.append(nums_less[k])
        return(result)

Insert picture description here

The method used is counting and sorting . This is the first time I have heard of this. The overall calculation method is as follows:

  • First initialize an array nums_tem with a length of 101, each position is 0 (used to temporarily store the number of occurrences of elements in nums, maybe this is the meaning of counting in counting sorting)
  • Then traverse nums, which number appears at the corresponding position of nums_tem +1 (count), so that we get the temporary count array we need (the subscript of the temporary array nums_tem corresponds to the element in nums, and the number on the subscript corresponds to the subscript in Number of occurrences in nums)
  • After that, we initialize another empty array nums_less (used to store the number of times that nums is less than a certain number)
  • Finally traverse nums and output the corresponding result

Guess you like

Origin blog.csdn.net/AWhiteDongDong/article/details/110271246