优先队列
c++优先队列priority_queue(自定义比较函数)_c++优先队列自定义比较-CSDN博客
373. 查找和最小的 K 对数字 - 力扣(LeetCode)
官方题解:
class Solution {
public:vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {auto cmp = [&nums1,&nums2](const pair<int,int>& a,const pair<int,int>& b) {return nums1[a.first] + nums2[a.second] > nums1[b.first] + nums2[b.second];};int m = nums1.size();int n = nums2.size();vector<vector<int>> ans;priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(cmp)> pq(cmp);for(int i = 0;i < min(k,m);i++) {pq.emplace(i,0);}while(k-- > 0 && !pq.empty()) {auto [x,y] = pq.top();pq.pop();ans.emplace_back(initializer_list<int>{nums1[x],nums2[y]});if(y + 1 < n) {pq.emplace(x,y + 1);}}return ans;}
};
c++优先队列(priority_queue)用法详解_c++ 优先队列-CSDN博客
count函数
[C++] 基础教程 - std::count函数介绍和使用场景_std::cout-CSDN博客
std::count 是C++标准库的一个算法,用来计算给定值在指定范围内出现的次数
template <class InputIt, class T>
size_t count(InputIt first, InputIt last, const T& value);
使用场景:
#include <iostream>
#include <vector>
#include <algorithm>int main() {std::vector<int> nums = {1, 2, 3, 4, 5, 2, 3, 2};int target = 2;size_t count = std::count(nums.begin(), nums.end(), target);std::cout << "The number " << target << " appears " << count << " times in the array." << std::endl;return 0;
}
#include <iostream>
#include <string>
#include <algorithm>int main() {std::string str = "hello world";char target = 'l';size_t count = std::count(str.begin(), str.end(), target);std::cout << "The character '" << target << "' appears " << count << " times in the string." << std::endl;return 0;
}