按频率安排

时间:2019-01-25 11:29:07

标签: c++ stdvector stdmap

任务:设计一个函数,使其首先返回具有最高频率元素的排序矢量对,如果两个元素具有相同频率,则按元素以排序顺序(递增)排列它们。

它在概念上有误吗?

是否可以进一步降低其复杂性

in:

1 2 4 8 4 9 2 0 9 4 2
out:数字频率
2 3 4 3 9 2 0 1 1 1 8 1

len(v):

10 ^ 6
v [i]:
10 ^ 15

#include <bits/stdc++.h>
using namespace std;

// sort function
bool mySort(pair<long long,long long> &a, pair<long long,long long>&b){
    if(a.second==b.second)
        return (a.first<b.first);
    else
        return (a.second>b.second);
}


vector<pair<long long, long long> > sortWithFrequency(vector<long long> v){

    vector<pair<long long, long long> > v_new;
    map<long long, long long> m;
    vector<long long>::iterator p= v.begin();


    while(p!=v.end()){
        m[*p]+=1;
        p++;
    }

   map<long long, long long>::iterator mp = m.begin();

    while(mp!=m.end()){
        v_new.push_back(pair<long long,long long>((*mp).first,(*mp).second));
        mp++;
    }

    sort(v_new.begin(), v_new.end(), mySort);

    return v_new;  
}

int main() {

    long long testcase;
    cin>>testcase;

    while(testcase--){
        long long N;
        cin >> N;

        // declaring vector
        vector<long long> v;

        for(long long i = 0;i<N;i++){
            long long k;
            cin >> k;
            v.push_back(k);
        }

    // calling function to perform required operation
        vector<pair<long long, long long> > v_new = sortWithFrequency(v);
        vector<pair<long long, long long> >::iterator it;

        for(it = v_new.begin();it!=v_new.end();it++){
            cout << it->first << " " << it->second << " ";
        }
        cout << endl;

    }


    return 0;
}

1 个答案:

答案 0 :(得分:2)

多图可以减少内存使用量:

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

int main() {

    std::vector<int> v = { 1, 2, 4, 8, 4, 9, 2, 0, 9, 4, 2 };
    std::for_each(v.begin(), v.end(), [](int i) { std::cout << i << " "; });
    std::cout << std::endl;

    std::map<int, size_t> m;
    std::multimap<size_t, int> mm;
    std::for_each(v.begin(), v.end(), [&](int i) { m[i]++; });
    std::for_each(m.begin(), m.end(), [&](std::pair<int, size_t> p) { mm.insert(std::pair<size_t, int>(p.second, p.first)); });
    std::for_each(mm.rbegin(), mm.rend(), [](std::pair<size_t, int> p) { std::cout << p.second << " " << p.first << " "; });
    std::cout << std::endl;

    return 0;
}