leetcode 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:
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.

這道題我用的是unordered_map,在不同的數都存下來之後 直接找最大值。(或者直接用桶排序也可以)

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> topk(k);
        unordered_map<int,int> hash;
        for (int i = 0; i < nums.size(); i++) {
            unordered_map<int,int>::iterator has = hash.find(nums[i]);
            if (has == hash.end()) hash[nums[i]] = 1;
            else (*has).second += 1;
        }
        unordered_map<int,int>::iterator it = hash.begin();
        int max = it->second;
        int pos = it->first;
        for (int i = 0; i < k; i++) {
            for (it = hash.begin(); it != hash.end(); it++) {
                if (it->second > max) {
                    max = it->second;
                    pos = it->first;
                }
            }
            topk[i] = pos;
            hash[pos] = 0;
            max = 0;
            pos = 0;
        }
        return topk;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章