堆排序——LeetCode347.Top K Frequent Elements

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hh66__66hh/article/details/82878236

堆排序——LeetCode347.Top K Frequent Elements

题目

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

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个数字。思路就是先统计每个整数出现的次数,然后对这些次数进行堆排序,然后从中选出前K大的数字返回。

代码


typedef struct node{
    int num;
    int ans;
};

class Solution {
public:
    vector<node>number;
    vector<node>heap;
    vector<int>res;
    int kth;

    void maximum(int i, int heap_size) {
        int l, r, m;
        node temp;
        l = i*2;
        r = i*2 + 1;
        m = i;
        temp = heap[i-1];
        if(l<=heap_size && heap[l-1].ans>heap[m-1].ans) {
            m = l;
            temp = heap[l-1];
        }
        if(r<=heap_size && heap[r-1].ans>heap[m-1].ans) {
            m = r;
            temp = heap[r-1];
        }
        if(m!=i) {
            heap[m-1] = heap[i-1];
            heap[i-1] = temp;
            maximum(m, heap_size);
        }
    }

    void heap_build() {
        int i, j;
        heap.clear();
        for(i=0; i<number.size(); i++) {
            heap.push_back(number[i]);
        }
        for(i=heap.size()/2; i>0; i--) {
            maximum(i, heap.size());
        }

    }

    void heap_sort() {
        int i, j, hl;
        node temp;
        heap_build();
        hl = heap.size();
        while(hl>1) {
            temp = heap[hl-1];
            heap[hl-1] = heap[0];
            heap[0] = temp;
            maximum(1, hl-1);
            hl--;
        }



    }

    vector<int> topKFrequent(vector<int>& nums, int k) {
        kth = k;
        number.clear();
        map<int, int> m;
        map<int, int>::iterator iter;
        m.clear();
        int i, j, t;
        for(i=0; i<nums.size(); i++) {
            t = nums[i];
            if(m.count(t)<0) {
                m[t] = 0;
            }
            else {
                m[t]++;
            }
        }
        iter = m.begin();
        j = 0;
        while(iter!=m.end()) {
            node t;
            t.num = iter->first;
            t.ans = iter->second;
            number.push_back(t);
            iter++;
        }
        heap_sort();

        res.clear();

        int ij = heap.size();
        for(i=0; i<kth; i++) {
            res.push_back(heap[ij-i-1].num);
        }
        return res;

    }
};

猜你喜欢

转载自blog.csdn.net/hh66__66hh/article/details/82878236