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

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

1. Description

How Many Numbers Are Smaller Than the Current Number

2. Solution

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

  • Version 1
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
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
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
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/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值