文章作者: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
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
- https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/