思路:
首先我们要理解问题,小C需要点一些价格相同的菜,且这些菜的价格不能超过给定的上限 m,目标是找到在价格不超过 m 的情况下,数量最多的那种价格的菜。所以根据要求可以使用一个 HashMap 来统计每种价格的菜的数量,遍历数组 w,将每种价格的菜的数量记录在 HashMap 中。然后我们可以用三步来解决:
-
初始化一个
HashMap来存储每种价格的菜的数量。 -
遍历数组
w,对于每个价格w[i],如果w[i]小于等于m,则在HashMap中增加该价格的计数。 -
遍历
HashMap,找到数量最多的那种价格的菜的数量。 它的代码框架:import java.util.HashMap; public class Main { public static long solution(int m, int[] w) { // 初始化一个 HashMap 来存储每种价格的菜的数量 HashMap<Integer, Integer> priceCount = new HashMap<>(); // 遍历数组 w,统计每种价格的菜的数量 for (int price : w) { if (price <= m) { // 如果价格小于等于 m,则在 HashMap 中增加该价格的计数 priceCount.put(price, priceCount.getOrDefault(price, 0) + 1); } } // 初始化最大数量为 0 int maxCount = 0; // 遍历 HashMap,找到数量最多的那种价格的菜的数量 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); } }
解释一下要注意以下三点:
- HashMap:用于存储每种价格的菜的数量。
- 遍历数组
w:统计每种价格的菜的数量,并存储在HashMap中。 - 遍历
HashMap:找到数量最多的那种价格的菜的数量。
通过这种方式,我们可以有效地解决小C点菜问题。