题解 | #最小的K个数#

最小的K个数

http://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf

大根堆

public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> ans;
        int n = input.size();
        if(k > n) return ans;
        priority_queue<int> max_heap;    // 创建最大堆

        for(int i = 0; i < input.size(); i++){
            if(max_heap.size() < k) max_heap.push(input[i]);    // 堆的大小不足k
            else{
                if(max_heap.size() && input[i] < max_heap.top()){    // 堆若不空, 则把当前元素与堆顶比较
                    max_heap.pop();
                    max_heap.push(input[i]);
                }
            }
        }

        while(max_heap.size()){        // 取出堆中的k个元素
            ans.push_back(max_heap.top());
            max_heap.pop();
        }

        return ans;
    }
};
全部评论

相关推荐

面向对象的火龙果很爱...:去吃一顿炸鸡就走
点赞 评论 收藏
分享
07-02 22:46
门头沟学院 Java
码农索隆:hr:“管你投没投,先挂了再说”
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务