一些易忘的细节
1、priority_queue自定义比较结构
class Solution { public: struct cmp { bool operator()(int &a, int &b) const { //因为优先出列判定为!cmp,所以反向定义实现最小值优先 return a>b; } }; vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { if (input.size() == 0 || k == 0 || k > input.size()) return {}; /*int start = 0, end = input.size()-1; int index = partition(input, start, end); while (index != k) { if (index > k-1) { end = } }*/ priority_queue<int, vector<int>, cmp> pq; for (int i = 0; i < input.size(); i++) { pq.push(input[i]); } vector<int> ans; for (int i = 0; i < k && !pq.empty(); i++) { ans.push_back(pq.top()); pq.pop(); } return ans; } };
leetcode767:
class Solution { public: string reorganizeString(string S) { vector<int> cnt(26, 0); for (int i = 0; i < S.size(); i++) { cnt[S[i]-'a']++; if (cnt[S[i]-'a'] > (S.size()+1)/2) return ""; } auto cmp = [&cnt](int i, int j) { return cnt[i] < cnt[j]; }; priority_queue<int, vector<int>, decltype(cmp)> pq(cmp); for (int i = 0; i < 26; i++) if (cnt[i] > 0) pq.push(i); for (int i = 0, prev = -1; i < S.size(); i++) { int j = pq.top(); pq.pop(); S[i] = 'a'+j; if (prev >= 0) pq.push(prev); prev = --cnt[j] <= 0 ? -1 : j; } return S; } };