题目
小C来到了一家餐馆,准备点一些菜。
已知该餐馆有 n 道菜,第 i 道菜的售价为 wi。
小C准备点一些价格相同的菜,但小C不会点单价超过 m 的菜。
小C想知道,自己最多可以点多少道菜?
代码思路
数据结构选择:
- 使用 `HashMap<Integer, Integer>` 来统计每种价格的菜的数量。键是菜品的价格,值是该价格菜品的数量。
算法步骤:
- **遍历价格数组**:遍历 `w` 数组中的每个价格。
- **统计价格数量**:
- 如果当前价格 `price` 不超过 `m`,则将其加入 `priceCount` 哈希表中,并更新该价格的菜品数量。
- **找出最大数量**:
- 遍历 `priceCount` 哈希表中的所有值,找出数量最多的那种菜品的价格数量。
返回结果:
- 返回找到的最大数量。
代码
import java.text.StringCharacterIterator;
import java.util.HashMap;
public class Main {
public static long solution(int m, int[] w) {
// 创建一个哈希表来统计每种价格的菜的数量
HashMap<Integer, Integer> priceCount = new HashMap<>();
// 遍历价格数组,统计每种价格的菜的数量
for (int price : w) {
if (price <= m) {
// 统计每种价格的菜的数量
priceCount.put(price, priceCount.getOrDefault(price, 0) + 1);
}
}
// 找出数量最多的那种价格的菜的数量
int maxCount = 0;
for (int count : priceCount.values()) {
// 更新最大数量
if (count > maxCount){
maxCount = count;
}
}
return maxCount;
}
public static void main(String[] args) {
System.out.println(solution(6, new int[]{2, 3, 3, 6, 6, 6, 9, 9, 23}) == 3);
System.out.println(solution(4, new int[]{1, 2, 4, 4, 4}) == 3);
System.out.println(solution(5, new int[]{5, 5, 5, 5, 6, 7, 8}) == 4);
}
}
这段代码的功能是解决“小C点菜问题”,即在给定的菜品价格数组中,找出单价不超过某个上限 `m` 的菜品中,数量最多的那种菜品的价格数量。
代码功能解释
输入参数:
- `int m`:表示小C愿意支付的最高单价。
- `int[] w`:表示餐馆中所有菜品的价格数组。
输出:
- 返回一个 `long` 类型的值,表示单价不超过 `m` 的菜品中,数量最多的那种菜品的价格数量。
代码解释
- HashMap<Integer, Integer> priceCount:用于存储每种价格的菜品数量。
- for (int price : w):遍历菜品价格数组
w。 - if (price <= m):检查当前价格是否不超过
m。 - priceCount.put(price, priceCount.getOrDefault(price, 0) + 1):更新哈希表中该价格的菜品数量。
- for (int count : priceCount.values()):遍历哈希表中的所有数量值,找出最大值。
- return maxCount:返回找到的最大数量。
总结
这段代码通过使用哈希表来统计每种价格的菜品数量,并通过遍历哈希表来找出数量最多的那种菜品的价格数量,从而解决了“小C点菜问题”。