1000万条有重复的字符串,找出重复数前10的字符串

本文介绍了如何通过使用小根堆优化数据处理过程,特别是针对频繁出现的数值进行排序时的效率提升。通过比较两种方法,即使用标准排序算法和引入小根堆的方法,阐述了在特定场景下选择合适的数据结构的重要性,从而实现资源的有效利用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入的时候可以使用map来存储,然后将map里的数据转到vector里,把重复数num按从大到小来排序之后,vector输出前10个即可。

 

#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
using namespace std;

map<string, int> mp;
struct node {
    string s;
    int num;
    node(string s,int num):s(s),num(num){}
};
vector<node> v;

bool cmp(const node&a, const node&b) {
    return a.num > b.num;
}

int main() {
    int n, m, i;
    string s;
    cin >> n;
    for (i=0; i<n; i++) {
        cin >> s;
        if (mp.find(s) != mp.end()) {
            mp[s] ++;
        } else {
            mp.insert(make_pair(s, 1));
        }
    }
    map<string,int>::iterator it;
    for (it=mp.begin(); it!=mp.end(); it++) {
        node x(it->first, it->second);
        v.push_back(x);
    }
    sort(v.begin(), v.end(), cmp);
    for (i=0; i<10; i++) {
        cout << v[i].s << endl;
    }
    return 0;
}

   

上面的做法其实在vector排序中是挺低效的,因为我们只需要找出10条信息,却把所有信息都排序了一边。

为了避免这样的时间浪费,可以使用一个只有10个元素的小根堆,不断地维护堆顶元素,使用迭代器把map遍历一遍之后,得到的小根堆里的10个元素就是所求答案了。

 

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <queue>
#include <functional>
using namespace std;


map<string, int> mp;

struct node {
    string s;
    int num;
    node(string s=NULL,int num=0):s(s),num(num){}
};


struct cmp{
    bool operator () (const node& a, const node& b) const {
        return a.num > b.num;
    }
};

priority_queue<node, vector<node>, cmp> pq;

int main() {
    int n, m, i;
    string s;
    cin >> n;
    for (i=0; i<n; i++) {
        cin >> s;
        if (mp.find(s) != mp.end()) {
            mp[s] ++;
        } else {
            mp.insert(make_pair(s, 1));
        }
    }
    map<string,int>::iterator it;
    for (it=mp.begin(), i=0; it!=mp.end(); it++, i++) {
        if (i < 10) {
            node x(it->first, it->second);
            pq.push(x);
        } else {
            node x(it->first, it->second);
            if (it->second > pq.top().num){
                pq.pop();
                pq.push(x);
            }
        }
    }

    while (!pq.empty()) {
        cout << pq.top().s << endl;
        pq.pop();
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/marginalman/p/4808888.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值