本文共 847 字,大约阅读时间需要 2 分钟。
class Solution { public: vector GetLeastNumbers_Solution(vector input, int k) { priority_queue max_heap; vector results; if(input.size() < k || k<=0) return results; for(auto& val: input) { // 堆还不够最小的容量,直接加进去 if(max_heap.size() < k) { max_heap.push(val); } //让当前元素与队顶元素相比 else if (max_heap.top() > val) { max_heap.push(val);// 当前元素入队 max_heap.pop(); } } while(max_heap.size()) { results.push_back(max_heap.top()); max_heap.pop(); } reverse(results.begin(), results.end()); return results; }};
转载地址:http://snklf.baihongyu.com/