力扣3527题解:去重统计与字典序排序的完美结合

一、问题理解
我们需要处理一个二维字符串数组,统计每个字符串在所有子数组中出现过的天数(每个子数组内相同字符串只计一次),然后找出出现频率最高的字符串。
二、算法设计思路
三、关键实现细节
高效去重:利用unordered_set的O(1)查找特性
频率统计:unordered_map提供O(1)的插入和查询
结果比较:同时比较频率和字典序
四、代码实现
class Solution {
public:
string findCommonResponse(vector<vector<string>>& responses) {
unordered_map<string, int> freq;
// 统计每个回答出现的天数(每个子数组内去重)
for (auto& day_responses : responses) {
unordered_set<string> day_set(day_responses.begin(), day_responses.end());
for (const auto& response : day_set) {
freq[response]++;
}
}
string result;
int max_count = 0;
// 找出出现频率最高且字典序最小的回答
for (const auto& [response, count] : freq) {
if (count > max_count ||
(count == max_count && response < result)) {
max_count = count;
result = response;
}
}
return result;
}
};原创内容 转载请注明出处
