码迷,mamicode.com
首页 > 其他好文 > 详细

top-k-frequent-elements

时间:2016-05-02 15:41:03      阅读:419      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/top-k-frequent-elements/

 

class minHeap {
// min Heap
private:
    vector<pair<int, int> > array;
    int alen;
    
    void adjust_all() {
        for (int k=alen-1; k>=0; --k) {
            adjust(k);
        }
    }
    
    void swap(int i, int j) {
        int tmp = array[i].first;
        array[i].first = array[j].first;
        array[j].first = tmp;
        
        tmp = array[i].second;
        array[i].second = array[j].second;
        array[j].second = tmp;
    }
    
    void adjust(int k) {
        if (k*2+1 >= alen) {
            return;
        }
        int j = k * 2 + 1;
        if (k*2+2 < alen && array[k*2+1].second > array[k*2+2].second) {
            j = k * 2 + 2;
        }
        if (array[k].second > array[j].second) {
            swap(k, j);
            adjust(j);
        }
    }
    
public:
    minHeap(int n) {
        alen = n;
    }

    void add(int num, int freq) {
        if (array.size() < alen) {
            array.push_back(make_pair(num, freq));
            if (array.size() == alen) {
                adjust_all();
            }
        }
        else {
            if (freq > array[0].second) {
                array[0].first = num;
                array[0].second = freq;
                adjust(0);
            }
        }
    }
    
    vector<int> getArray() {
        vector<int> ret;
        for (int k=alen-1; k>=0; --k) {
            ret.push_back(array[k].first);
        }
        return ret;
    }

};

class Solution {
    unordered_map<int, int> umap;
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        int vlen = nums.size();
        for (int i=0; i<vlen; ++i) {
            if (umap.find(nums[i]) != umap.end()) {
                umap[nums[i]] = umap[nums[i]] + 1;
            }
            else {
                umap[nums[i]] = 1;
            }
        }
        
        minHeap mh(k);
        for (unordered_map<int, int>::iterator itr = umap.begin();
             itr != umap.end(); ++itr) {
        
            mh.add(itr->first, itr->second);         
        }
        return mh.getArray();
    }
};

 

top-k-frequent-elements

标签:

原文地址:http://www.cnblogs.com/charlesblc/p/5452403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!