代码一:用字典。
class Solution(object):
def smallerNumbersThanCurrent(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
mydict = {}
temp = []
for i, v in enumerate(nums):
temp.append(i)
if v in mydict.keys():
mydict[v] += temp
else:
mydict[v] = temp
temp = []
newList = sorted(mydict.items(), key=lambda item: item[0], reverse=True)
# print(newList)
# 记录原list的元素个数
count = len(nums)
ans = [0 for _ in range(count)]
for i in range(len(newList)):
# 同值元素的下标
indexList = newList[i][1]
# 更新计数器
count -= len(indexList)
# 同值元素的结果相同
for index in indexList:
ans[index] = count
return ans
代码二:暴力。
class Solution(object):
def smallerNumbersThanCurrent(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ans = []
for i in nums:
ans.append(self.smallCount(nums, i))
return ans
# 统计数组中比n小的数的个数
def smallCount(self, nums, n):
if not nums:
return 0
ans = 0
for item in nums:
if item < n:
ans += 1
return ans