问题描述
小C想要点一些价格相同的菜,并且这些菜的价格不能超过给定的上限 m。我们需要找出在满足这个条件下,小C最多可以点多少道菜。
数据结构选择
为了快速统计每种价格的菜的数量,我们选择使用哈希表(std::unordered_map)。哈希表可以在常数时间内插入和查找元素,非常适合用于统计和查找。
算法步骤
- 过滤价格:遍历价格数组,只保留那些价格不超过
m的菜。 - 统计数量:使用哈希表统计每种价格的菜的数量。
- 找出最大值:遍历哈希表,找出数量最多的那种价格的菜的数量。
代码实现
#include <iostream>
#include <vector>
#include <unordered_map> // 包含必要的头文件
using namespace std;
long solution(int m, const std::vector<int> w) {
// 创建一个哈希表来统计每种价格的菜的数量
std::unordered_map<int, int> priceCount;
// 遍历价格数组,统计每种价格的菜的数量
for (int price : w) {
if (price <= m) {
priceCount[price]++;
}
}
// 找出数量最多的那种价格的菜的数量
int maxCount = 0;
for (const auto& pair : priceCount) {
if (pair.second > maxCount) {
maxCount = pair.second;
}
}
return maxCount;
}
int main() {
std::cout << (solution(6, {2, 3, 3, 6, 6, 6, 9, 9, 23}) == 3) << std::endl;
std::cout << (solution(4, {1, 2, 4, 4, 4}) == 3) << std::endl;
std::cout << (solution(5, {5, 5, 5, 5, 6, 7, 8}) == 4) << std::endl;
return 0;
}
代码解释
-
包含必要的头文件:
#include <unordered_map>确保包含
<unordered_map>头文件,以便使用std::unordered_map。 -
创建哈希表:
std::unordered_map<int, int> priceCount;创建一个哈希表
priceCount,用于统计每种价格的菜的数量。 -
遍历价格数组:
for (int price : w) { if (price <= m) { priceCount[price]++; } }遍历价格数组
w,只保留那些价格不超过m的菜,并在哈希表中统计每种价格的菜的数量。 -
找出最大值:
int maxCount = 0; for (const auto& pair : priceCount) { if (pair.second > maxCount) { maxCount = pair.second; } }遍历哈希表
priceCount,找出数量最多的那种价格的菜的数量。 -
返回结果:
return maxCount;返回数量最多的那种价格的菜的数量。
总结
通过使用哈希表,我们可以在常数时间内统计每种价格的菜的数量,并通过遍历哈希表找出数量最多的那种价格的菜的数量。这种方法简单高效,适合解决这类统计问题。