Leetcode 1365. How Many Numbers Are Smaller Than the Current Number

2021-07-08 16:22:47 浏览数 (1)

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

**解析:**Version 1是两两比较所有的数,简单直接。Version 2,由于所有的数都在[0, 100]之间,因此统计[0,100]之间的数字个数即可,比98小的数是[0,97]之间数字的个数之和。Version 3是Version 2的通用版,不用限制数字的大小。Version 4是进一步优化,只统计出现的数字数量。

  • Version 1
代码语言:javascript复制
class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        n = len(nums)
        result = [0 for _ in range(n)]
        for i in range(n):
            for j in range(i 1, n):
                if nums[i] > nums[j]:
                    result[i]  = 1
                elif nums[i] < nums[j]:
                    result[j]  = 1
        return result
  • Version 2
代码语言:javascript复制
class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        stat = {i: 0 for i in range(101)}
        for num in nums:
            stat[num] = stat.get(num, 0)   1

        count = 0
        for i in range(101):
            pre = count
            count  = stat[i]
            stat[i] = pre

        result = [stat[num] for num in nums]
        return result
  • Version 3
代码语言:javascript复制
class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        maximun = max(nums)
        stat = {i: 0 for i in range(maximun 1)}
        for num in nums:
            stat[num] = stat.get(num, 0)   1

        count = 0
        for i in range(maximun 1):
            pre = count
            count  = stat[i]
            stat[i] = pre

        result = [stat[num] for num in nums]
        return result
  • Version 4
代码语言:javascript复制
class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        order = sorted(set(nums))
        stat = {num: 0 for num in order}
        for num in nums:
            stat[num] = stat.get(num, 0)   1

        count = 0
        for num in order:
            pre = count
            count  = stat[num]
            stat[num] = pre

        result = [stat[num] for num in nums]
        return result

Reference

  1. https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/

0 人点赞