From 09756aeff11260140f366e2aebc11f15405d7ea4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8A=B1=E6=97=A0=E7=BC=BA?= Date: Tue, 4 Apr 2023 15:10:09 +0800 Subject: [PATCH] fix sort-characters-by-frequency --- .../solution_code.md" | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git "a/345円244円232円350円257円255円350円250円200円350円247円243円346円263円225円344円273円243円347円240円201円/solution_code.md" "b/345円244円232円350円257円255円350円250円200円350円247円243円346円263円225円344円273円243円347円240円201円/solution_code.md" index 3b6a969080..c3918afc27 100644 --- "a/345円244円232円350円257円255円350円250円200円350円247円243円346円263円225円344円273円243円347円240円201円/solution_code.md" +++ "b/345円244円232円350円257円255円350円250円200円350円247円243円346円263円225円344円273円243円347円240円201円/solution_code.md" @@ -59599,35 +59599,34 @@ https://leetcode.cn/problems/sort-characters-by-frequency 的多语言解法👇 class Solution { public: string frequencySort(string s) { - char[] chars = s.toCharArray(); + vector chars(s.begin(), s.end()); // s 中的字符 -> 该字符出现的频率 unordered_map charToFreq; for (char ch : chars) { - charToFreq[ch] = charToFreq[ch] + 1; + charToFreq[ch]++; } - priority_queue, vector>, function, pair)>> - pq([](const pair& entry1, const pair& entry2) -> bool { - // 队列按照键值对中的值(字符出现频率)从大到小排序 - return entry2.second < entry1.second; - }); + auto cmp = [](pair& entry1, pair& entry2) { + return entry1.second < entry2.second; + }; + // 队列按照键值对中的值(字符出现频率)从大到小排序 + priority_queue, vector>, decltype(cmp)> pq(cmp); // 按照字符频率排序 - for (const auto& entry : charToFreq) { + for (auto& entry : charToFreq) { pq.push(entry); } - string res; + string res = ""; while (!pq.empty()) { // 把频率最高的字符排在前面 pair entry = pq.top(); pq.pop(); - string part(entry.second, entry.first); - res.append(part); + res += string(entry.second, entry.first); } return res; - } + } }; ```

AltStyle によって変換されたページ (->オリジナル) /