剑指offer:最小的K个数(大根堆)

题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

 

思路:维护一个大根堆,pop掉大的数,剩下的就是K小,O(nlogn)。

手写堆或者STL

class Solution {
public:
    int *a, tot=0;
    int top(){
        return a[1];
    }
    void pop(){
        a[1] = a[tot--];
        for(int i=1, j=i<<1; j<=tot; i=j, j=i<<1){
            if(j+1 <= tot && a[j+1]>a[j]) ++j;
            if(a[i] < a[j]) swap(a[i], a[j]);
            else break;
        }
    }
    void push(int x, int k){
        if(tot >= k){
            if(top() <= x) return;
            else pop();
        }
        a[++tot] = x;
        for(int i=tot, j=i>>1; j>0; i=j, j=i>>1){
            if(a[i] > a[j]) swap(a[i], a[j]);
            else break;
        }
    }
    vector GetLeastNumbers_Solution(vector input, int k) {
        int len = input.size();
        vectorans;
        if(k<=0 || k>len) return ans;
        a = new int[len+3];
        for(int i=0; i
class Solution {
public:
    vector GetLeastNumbers_Solution(vector input, int k) {
        priority_queueq;
        vectorans;
        int len = input.size();
        if(k <= 0 || k > len) return ans;
        for(int i=0; i= k) q.pop();
        }
        while(!q.empty()){
            ans.push_back(q.top());
            q.pop();
        }
        return ans;
    }
};

 

你可能感兴趣的:(笔试题目/套题)