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

    347. Top K Frequent Elements

    • Total Accepted: 26456
    • Total Submissions: 60329
    • Difficulty: Medium

    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: 

    • You 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.

    思路:最好的是桶排序,牺牲了内存,加快了速度。总的来说,可以有O(n)和O(nlog(n-k))两种做法。

    代码:

    O(n)的做法:

     1 class Solution {
     2 public:
     3     vector<int> topKFrequent(vector<int>& nums, int k) {
     4         unordered_map<int,int> um;
     5         for(int num:nums){
     6             um[num]++;
     7         }
     8         vector<vector<int> > bucket(nums.size()+1);
     9         for(auto p:um){
    10             bucket[p.second].push_back(p.first);
    11         }
    12         vector<int> res;
    13         for(int i=bucket.size()-1;i>=0&&res.size()<k;i--){
    14             for(int num:bucket[i]){
    15                 res.push_back(num);
    16                 if(res.size()==k){
    17                     break;
    18                 }
    19             }
    20         }
    21         return res;
    22     }
    23 };

    O(nlog(n-k))的做法:

     1 class Solution {
     2 public:
     3     vector<int> topKFrequent(vector<int>& nums, int k) {
     4         unordered_map<int,int> um;
     5         for(int num:nums){
     6             um[num]++;
     7         }
     8         vector<int> res;
     9         priority_queue<pair<int,int> > pq;
    10         for(auto it=um.begin();it!=um.end();it++){
    11             pq.push(make_pair(it->second,it->first));
    12             if(pq.size()>um.size()-k){//抽屉原理
    13                 res.push_back(pq.top().second);
    14                 pq.pop();
    15             }
    16         }
    17         return res;
    18     }
    19 };

    11号到22号,杂七杂八的事情有些多,耽搁了一段时间。

  • 相关阅读:
    通信专业术语解释
    STM32F10系列管脚设置
    [笔试题]使用回调函数编写冒泡排序,可以排序整形数组,也可以排序字符串
    Date常用转换、比较
    哈希映射
    APP技巧格式
    $.get/$.post/$.ajax/$.getJSON
    使用Rss框架PHP开发流程
    测试rss与navicat连接
    验证码技术
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5794254.html
Copyright © 2011-2022 走看看