1365. How Many Numbers Are Smaller Than the Current Number

Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].

Return the answer in an array.

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

先用hash table count[i]来记录每个数出现的次数,得到这个count之后再对这个count求前缀和,count[i]就表示小于等于i的数的个数。

class Solution(object):
    def smallerNumbersThanCurrent(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        count = [0] * 101
        for num in nums:
            count[num] += 1
        for i in range(1, 101, 1):
            count[i] += count[i - 1]
        ans = []
        for num in nums:
            if num == 0:
                ans.append(0)
            else:
                ans.append(count[num - 1])
        return ans
            

 

posted @ 2020-06-28 21:40  whatyouthink  阅读(40)  评论(0编辑  收藏  举报