工程化實現題
# class Solution:
# def minimumTimeRequired(self, jobs: List[int], k: int) -> int:
# self.record_dict = collections.defaultdict(list)
# self.count = 0
class SkiRankingSystem:
def __init__(self):
self.record_dict = collections.defaultdict(list)
self.count = 0
# addRecord(int userId, int duration)
# 添加一條滑雪記錄,同一個userId可以添加多條滑雪記錄
def add_record(self, user_id: int, duration: int) -> None:
self.count += 1
self.record_dict[user_id].append((duration, self.count))
self.record_dict[user_id].sort()
# int[] getTopAthletes(int num)
# 返回滑雪最快的前num個運動員,用數組返回,按照滑雪時間由低往高排,如果時間相同則按照記錄的先後順序返回
def get_top_athletes(self, num: int) -> List[int]:
athletes = sorted(self.record_dict.items(), key=lambda item: (item[1][0][0], item[1][0][1]))
# item[1]是取value,因為item[0]是key
# item[1][0]是取每個運動員最小的duration,因為前面記錄的時候把最小的duration排最前面了
# item[1][0][0]是最小時長記錄的duration,item[1][0][1]是最小時長記錄的記錄順序,對應題目中“如果時間相同則按照記錄的先後順序返回”的要求
result = []
for i in athletes[:num]:
result.append(i[0])
print("get_top_athletes:", result)
print("athletes:",athletes)
return result
# int[] queryTop3Record(int userId)
# 返回一個運動員滑得最快的3次記錄,(注意此處的數據可以重複,同一個運動員可以多次滑雪時間相同,如果相同也需要返回)
def query_top3_record(self, user_id: int) -> List[int]:
record = self.record_dict[user_id][:3]
print("query_top3_record:", record)
return [i[0] for i in record]
# 用例
add_record(self, 1, 5)
add_record(self, 1, 33)
add_record(self, 1, 22)
add_record(self, 1, 44)
add_record(self, 2, 8)
add_record(self, 3, 44)
add_record(self, 4, 11)
add_record(self, 4, 5)
print("list1:", self.record_dict)
get_top_athletes(self, 4)
add_record(self, 3, 8)
query_top3_record(self, 1)
print("list2:", self.record_dict)
# stdout
# list1: defaultdict(<class 'list'>, {1: [(5, 1), (22, 3), (33, 2), (44, 4)], 2: [(8, 5)], 3: [(44, 6)], 4: [(5, 8), (11, 7)]})
# get_top_athletes: [1, 4, 2, 3]
# athletes: [(1, [(5, 1), (22, 3), (33, 2), (44, 4)]), (4, [(5, 8), (11, 7)]), (2, [(8, 5)]), (3, [(44, 6)])]
# query_top3_record: [(5, 1), (22, 3), (33, 2)]
# list2: defaultdict(<class 'list'>, {1: [(5, 1), (22, 3), (33, 2), (44, 4)], 2: [(8, 5)], 3: [(8, 9), (44, 6)], 4: [(5, 8), (11, 7)]})
# 輸入示例1:
# SkiRankingSystem sys = new SkiRankingSystem();
# sys.addRecord(1, 10);
# sys.addRecord(2, 8);
# sys.getTopAthletes(3); 返回[2,1]
# sys.queryTop3Record(1); 返回[10]
# 輸入示例2:
# SkiRankingSystem sys = new SkiRankingSystem();
# sys.addRecord(20, 8);
# sys.addRecord(22, 6);
# sys.addRecord(20, 6);
# sys.getTopAthletes(4);#返回[22, 20];
# sys.addRecord(33, 5);
# sys.addRecord(22, 9);
# sys.addRecord(31, 4);
# sys.getTopAthletes(4);#返回[31, 33, 22, 20];
# sys.addRecord(20, 8);
# sys.queryTop3Record(20);#返回[6, 8, 8]
# sys.addRecord(20, 6);
# sys.queryTop3Record(20);#返回[6, 6, 8]