精華區beta Marginalman 關於我們 聯絡資訊
https://leetcode.com/problems/design-a-food-rating-system/description 2353. Design a Food Rating System 設計一個食物排名系統。 FoodRatings(String[] foods, String[] cuisines, int[] ratings) 初始化食物排名系統。 void changeRating(String food, int newRating) 改變某個食物的等級。 String highestRated(String cuisine) 獲取某個國家等級最高的食物,如果等級一樣取名稱字典順序較高的。 思路: 1.先做初始化,我們把每個國家的食物保存在一個Heap裡面(用等級和名稱排序),每 個國家用Map去取。 2.如果要改變某個食物的等級,用一個全局Map去記錄最新的值,然後不管舊的值直接 push一個新的object到Heap裡面。 3.要取最高的時候就檢查指定的Heap的頂端,如果頂端元素的等級不等於全局Map記錄的 level,那就表示這個元素已經是舊的值了,把這個元素POP掉直到頂端元素的level相 同。 Java Code: --------------------------------------------------------------- class FoodRatings { private Map<String, PriorityQueue<KeyValue>> map; private Map<String, KeyValue> levelMap; public FoodRatings(String[] foods, String[] cuisines, int[] ratings) { map = new HashMap<>(); levelMap = new HashMap<>(); for (int i = 0; i < foods.length; i++) { if (!map.containsKey(cuisines[i])) { map.put(cuisines[i], new PriorityQueue<>((a, b) -> { if (a.level == b.level) { return a.name.compareTo(b.name); } else { return b.level - a.level; } })); } map.get(cuisines[i]).offer(new KeyValue(foods[i], ratings[i])); levelMap.put(foods[i], new KeyValue(cuisines[i], ratings[i])); } } public void changeRating(String food, int newRating) { KeyValue kv = levelMap.get(food); kv.level = newRating; map.get(kv.name).offer(new KeyValue(food, newRating)); } public String highestRated(String cuisine) { PriorityQueue<KeyValue> pq = map.get(cuisine); while (!pq.isEmpty()) { KeyValue kv = pq.peek(); if (kv.level != levelMap.get(kv.name).level) { pq.poll(); } else { return kv.name; } } return ""; } } class KeyValue { String name; int level; public KeyValue(String name, int level) { this.name = name; this.level = level; } } --------------------------------------------------------------- 今天寫的不是很好捏 雖然Runtime 93%但可讀性是0 你讀的懂算我輸 -- https://i.imgur.com/Df746ya.jpg -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1702834384.A.0F9.html
oin1104: 大師 12/18 01:37
NTUEE2CS: 大師 12/18 06:15