347. Top K Frequent Elements

来源:互联网 发布:广义线性模型 知乎 编辑:程序博客网 时间:2024/06/04 18:34

题目:

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.


题意:

给定一个非空的整数数组,返回其前k个出现次数最多的元素。

note:

1、假设k总是有效的,1 ≤ k ≤ 唯一元素的个数;

2、算法的时间复杂度必须要好于O(n log n),这里的n值是数组的大小;


思路:

先使用map统计每个元素出现的次数,之后基于每个元素出现的次数构造“桶”,出现次数多的在桶中的后面,之后轮训桶,从出现次数多的数开始取,将出现次数大于k次的元素放到返回集合中。

代码:33ms

public class Solution {    public List<Integer> topKFrequent(int[] nums, int k) {                List<Integer>[] bucket = new List[nums.length+1];        Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();                for(int num : nums){  //统计数组中每个元素出现的次数,并存储到map集合中            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);        }                for(int key : frequencyMap.keySet()){ //轮训生成的map,生成桶            int frequency = frequencyMap.get(key);            if(bucket[frequency]==null){                bucket[frequency] = new ArrayList<>();            }            bucket[frequency].add(key);        }                List<Integer> result = new ArrayList<>();        //将桶中出现次数大于k的元素放到返回集中        for(int pos = bucket.length-1; pos>=0 && result.size()<k; pos--){            if(bucket[pos]!=null){                result.addAll(bucket[pos]);            }        }                return result;    }}

C++版:44ms

class Solution {public:    vector<int> topKFrequent(vector<int>& nums, int k) {                unordered_map<int, int> map;        for(int num : nums){            map[num]++;        }                vector<vector<int>> buckets(nums.size()+1);        for(auto m : map){            buckets[m.second].push_back(m.first);        }                vector<int> result;        for(int i=buckets.size()-1; i>=0 && result.size()<k; --i){            for(int num : buckets[i]){                result.push_back(num);                if(result.size()==k){                    break;                }            }        }                return result;    }};

C++版:36ms

<span style="color:#333333;">class Solution {public:    vector<int> topKFrequent(vector<int>& nums, int k) {                unordered_map<int, int> map;        for(int num : nums){  //统计每个元素出现的次数 map<first, second> first代表数组元素,second代表出现频率            map[num]++;        }                vector<int> result;        priority_queue<pair<int, int>> pq;  //pair<first, second> first代表出现频率,second代表数组元素<        for(auto it=map.begin(); it!=map.end(); it++){            pq.push(make_pair(it->second, it->first));            if(pq.size()>(int)map.size()-k){                result.push_back(pq.top().second);                pq.pop();            }        }                return result;    }};</span>


0 0
原创粉丝点击