字典序——附力扣周赛303P3题解
字典序
简介
一种排序方法:对于字符串,先按首字符排序,如果首字符相同,再按第二个字符排序,以此类推。
e.g., abc,abd,bcd,bdd,ddd。
字符串 x 的字典序比字符串 y 更小的前提是:x 在字典中出现的位置在 y 之前,也就是说,要么 x 是 y 的前缀,或者在满足 x[i] != y[i] 的第一个位置 i 处,x[i] 在字母表中出现的位置在 y[i] 之前。
实现方式
利用堆(heapq)的结构。
import heapq
a=[]
heapq.heappush(a,'abc')
heapq.heappush(a,'ddd')
heapq.heappush(a,'bdd')
heapq.heappush(a,'bcd')
heapq.heappush(a,'abd')
a # ['abc', 'abd', 'bdd', 'ddd', 'bcd']
heapq.heappop(a) # 'abc'
heapq.heappop(a) # 'abd'
heapq.heappop(a) # 'bcd'
heapq.heappop(a) # 'bdd'
heapq.heappop(a) # 'ddd'
力扣周赛303P3题解
传送门:统计理想数组的数目
核心思路:“堆存储,缓处理”
- 对于 changeRating 操作,直接往 cs 中记录,不做任何删除操作;
- 对于 highestRated 操作,查看堆顶的食物评分是否等于其实际值,若不相同则意味着对应的元素已被替换成了其他值,堆顶存的是个垃圾数据,直接弹出堆顶;否则堆顶就是答案。
import collections
import heapq
from typing import *
class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
self.mp, self.cd = {}, collections.defaultdict(list)
for f, c, r in zip(foods, cuisines, ratings):
self.mp[f] = [r, c]
heapq.heappush(self.cd[c], (-r, f))
def changeRating(self, f: str, nr: int) -> None:
self.mp[f][0] = nr
heapq.heappush(self.cd[self.mp[f][1]], (-nr, f))
def highestRated(self, c: str) -> str:
while self.mp[self.cd[c][0][1]][0] != -self.cd[c][0][0]:
heapq.heappop(self.cd[c])
return self.cd[c][0][1]

浙公网安备 33010602011771号