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