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

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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/

以上是关于Leetcode 1365. How Many Numbers Are Smaller Than the Current Number的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode --- 1365. How Many Numbers Are Smaller Than the Current Number 解题报告

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

1365. How Many Numbers Are Smaller Than the Current Number

1365. How Many Numbers Are Smaller Than the Current Number

算法1365. 有多少小于当前数字的数字(java / c / c++ / python / go / rust)

LeetCode 1365 - 寻找比 O(n^2) 更好的解决方案