【发布时间】:2021-01-04 19:37:32
【问题描述】:
我无法对其进行足够的优化以使其在给定的时间范围内运行。
可以在此处 (https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem) 找到完整的说明,但它们有点长。 我基本上有两个数组:一个是得分高的排行榜,另一个是玩家得分的列表。我必须输出另一个数组,其中包含每个分数的玩家排名(例如,第 1、第 4、第 8 为 1、4、8)。
这是我的功能,但功能很慢:
def climbingLeaderboard(ranked, player):
rankings = []
# Making it a set to remove duplicates
ranked = list(set(ranked))
# Sorting only once outside of loop
ranked.sort()
for score in player:
# Duplicates must be avoided at all times
if score not in ranked:
# Used to avoid sorting at every iteration
bisect.insort(ranked, score)
# List was sorted ascending, but I need it descending
# There were a -1 and +1 which offset each other in order to convert from index to ranking
result = len(ranked) - ranked.index(score)
rankings.append(result)
# I don't fully get why, but this part can be omitted
# rankings.remove(score)
return rankings
我使用 bisect.insort() 来避免为循环的每次迭代对列表进行排序。 我想最重要的部分是转换为 set 然后再转换为 list,但老实说我不知道如何进一步优化它。
【问题讨论】:
标签: python loops optimization