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
1
2
3
4
5
6
7
8
9
10
11
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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/
如果有收获,可以请我喝杯咖啡!