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

    传送门

    347. Top K Frequent Elements

       My Submissions
    Total Accepted: 1246 Total Submissions: 2777 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.

    Subscribe to see which companies asked this question

    Hide Tags
     Hash Table Heap
     
     
    题意:
    找出数组中出现次数最多的k个元素
     
    题解:
    用map统计每个元素出现的个数
    然后用 优先队列 或 排序 取出 前k个
     
    20 / 20 test cases passed.
    Status: 

    Accepted

    Runtime: 56 ms
     
     1 struct PP
     2 {
     3     int val;
     4     int count;
     5 }te;
     6 
     7 bool cmp(PP a,PP b)
     8 {
     9     return a.count > b.count;
    10 }
    11 
    12 class Solution {
    13 public:
    14     vector<int> topKFrequent(vector<int>& nums, int k) {
    15         int n = nums.size();
    16         vector<int> ans;
    17         vector<PP> temp;
    18         map<int,int> mp;
    19         int i;
    20         for(i = 0;i < n;i++){
    21             mp[ nums[i] ]++;
    22         }
    23         for(map<int,int>::iterator it = mp.begin();it != mp.end();it++){
    24             te.val = it -> first;
    25             te.count = it -> second;
    26             temp.push_back(te);
    27         }
    28         sort(temp.begin(),temp.end(),cmp);
    29         for(i = 0;i < k;i++){
    30             ans.push_back(temp[i].val);
    31         }
    32         return ans;
    33     }
    34 };
  • 相关阅读:
    audio_policy.conf说明(翻译)
    Qt
    linux C
    Linux C
    Linux C
    Qt
    Qt
    JSON
    JSON
    Qt
  • 原文地址:https://www.cnblogs.com/njczy2010/p/5454233.html
Copyright © 2011-2022 走看看