zoukankan      html  css  js  c++  java
  • 347. Top K Frequent Elements

    Given a non-empty array of integers, return the k most frequent elements.

    For example,
    Given [1,1,1,2,2,3] and k = 2, return [1,2].

    Note: 

      • 347. Top K Frequent ElementsYou may assume k is always valid, 1 ≤ k ≤ number of unique elements.
      • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

    ========

    题目:

    因为c++中提供的哈希表map,不能按照value进行排序,

    我们需要一个按照value值进行排序的数据结构,所以需要自定义一个.

    定义排序函数,static bool mykeyval(const keyval &l, const keyval &r){}

    利用自带的sort()函数就可以了.

    ====

    代码

    class Solution {
    public:
        struct keyval{
            int key;//数字
            int val;//数字出现的次数
            keyval(int k=0,int v=0):key(k),val(v){}
        };
        static bool mykeyval(const keyval &l,const keyval &r){
            return l.val>r.val;
        }
        vector<int> topKFrequent(vector<int>& nums, int k) {
            map<int,int> m;///key,multis
            vector<int> re;
            for(auto i: nums){
                m[i]++;
            }
            vector<keyval> tmp(m.size());
            int d = 0;
            for(auto i: m){
                tmp[d].key = i.first;
                tmp[d++].val = i.second;
            }
            sort(tmp.begin(),tmp.end(),mykeyval);
            for(int i = 0;i<k;i++){
                re.push_back(tmp[i].key);
            }
            return re;
        }
    };
  • 相关阅读:
    The password has to have a minimum of 6 characters, including at least 1 small letter, 1 uppercase letter and 1 number
    Angular i18n的技术分享、踩过的坑
    转: .Net 4.0 ExpandoObject 使用
    min_square
    KALMAN PYTHON
    双系统安装 win + ubuntu
    docker
    drl
    shell
    导航定位方案
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5608749.html
Copyright © 2011-2022 走看看