标签:int least etl 输入 back item 排序 begin push
代码:
1.普通人的大顶堆解法
class Solution { public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { if (k == 0 || k > input.size()) return {}; priority_queue<int> p; vector<int> ans; for(int i = 0; i < k; i++){ p.push(input[i]); } for(int i = k; i < input.size(); i++){ if(input[i] < p.top()){ p.pop(); p.push(input[i]); } } for(int i = 0; i < k; i++){ ans.push_back(p.top()); p.pop(); } return ans; } };
2.
普通人懒人解法
class Solution { public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { if(k > input.size() || input.empty()) return {}; vector<int> ans; sort(input.begin(), input.end()); for(int i = 0; i < k; i++){ ans.push_back(input[i]); } return ans; } };
3.
冒泡排序:
class Solution { public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { if(k > input.size() || input.empty()) return {}; vector<int> ans; for(int i = 0; i < k; i++){ for(int j = 0; j < input.size()-i - 1; j++){ if(input[j] < input[j+1]){ int tmp = input[j]; input[j] = input[j+1]; input[j+1] = tmp; } } ans.push_back(input[input.size()-i-1]); } return ans; } };
标签:int least etl 输入 back item 排序 begin push
原文地址:https://www.cnblogs.com/BillowJ/p/12730962.html