1365. 有多少小于当前数字的数字 - 力扣(LeetCode)
可以使用两种方法来解决这个问题:
方法 1:暴力枚举(O(n²))
直接遍历数组,对于每个元素 nums[i]
,统计比它小的元素个数。
def smallerNumbersThanCurrent(nums):
return [sum(1 for j in nums if j < i) for i in nums]
# 测试
nums = [8, 1, 2, 2, 3]
print(smallerNumbersThanCurrent(nums)) # 输出: [4, 0, 1, 1, 3]
方法 2:排序 + 哈希表(O(n log n))
先对 nums
进行排序,然后用哈希表记录每个数字的索引,最后遍历原数组填充答案。
def smallerNumbersThanCurrent(nums):
sorted_nums = sorted(nums) # 排序
num_dict = {} # 记录每个数字第一次出现的索引
for i, num in enumerate(sorted_nums):
if num not in num_dict: # 只记录第一次出现的索引
num_dict[num] = i
return [num_dict[num] for num in nums]
# 测试
nums = [8, 1, 2, 2, 3]
print(smallerNumbersThanCurrent(nums)) # 输出: [4, 0, 1, 1, 3]
这种方法比暴力法更快,适用于大数据量的情况。