当前位置:首页 > 力扣题解 > 力扣3527题解:去重统计与字典序排序的完美结合

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

9小时前力扣题解24

截图未命名.jpg 力扣3527题解:去重统计与字典序排序的完美结合 哈希表 频率统计 字典序排序 数据去重 多维数据分析 第1张

一、问题理解

我们需要处理一个二维字符串数组,统计每个字符串在所有子数组中出现过的天数(每个子数组内相同字符串只计一次),然后找出出现频率最高的字符串。

二、算法设计思路

  1. 去重处理‌:使用unordered_set对每天的回答去重

  2. 频率统计‌:使用unordered_map统计每个字符串出现的天数

  3. 结果筛选‌:遍历哈希表找出最高频率且字典序最小的字符串

三、关键实现细节

  1. 高效去重‌:利用unordered_set的O(1)查找特性

  2. 频率统计‌:unordered_map提供O(1)的插入和查询

  3. 结果比较‌:同时比较频率和字典序

四、代码实现

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;
    }
};


原创内容 转载请注明出处

分享给朋友:

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。