思路:根据值从大到小排序,然后在加的时候判断是否达到标签上限即可,一开始想用字典做,但是题目说是集合却连续出现两个8,因此使用元组+SortedList进行解决
python
class Solution:
def largestValsFromLabels(self, values: list[int], labels: list[int], numWanted: int, useLimit: int) -> int:
from sortedcontainers import SortedList
from collections import defaultdict
sorted_values = SortedList()
for num in range(0, len(labels)):
sorted_values.add((values[num], labels[num]))
total_sum = 0
label_dict = defaultdict(int)
for value_label in reversed(sorted_values):
value = value_label[0]
label = value_label[1]
if label_dict[label] < useLimit:
if numWanted > 0:
numWanted -= 1
total_sum += value
label_dict[label] += 1
else:
return total_sum
return total_sum