|
1 | 1 | class Solution {
|
2 |
| - public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, |
3 |
| - String[] supplies) { |
4 |
| - Map<String, Set<String>> ingredientToRecipeMap = new HashMap<>(); |
5 |
| - Map<String, Integer> recipeToIngredientCount = new HashMap<>(); |
| 2 | + public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) { |
| 3 | + Map<String, List<String>> map = new HashMap<>(); |
| 4 | + Map<String, Integer> ingredientCounter = new HashMap<>(); |
6 | 5 | for (int i = 0; i < recipes.length; i++) {
|
7 |
| - String recipe = recipes[i]; |
8 |
| - List<String> ingredientsForRecipe = ingredients.get(i); |
9 |
| - recipeToIngredientCount.put(recipe, ingredientsForRecipe.size()); |
10 |
| - for (String ingredient : ingredientsForRecipe) { |
11 |
| - ingredientToRecipeMap.computeIfAbsent(ingredient, k -> new HashSet<>()).add(recipe); |
| 6 | + List<String> currentIngredientList = ingredients.get(i); |
| 7 | + for (String ingredient : currentIngredientList) { |
| 8 | + map.computeIfAbsent(ingredient, k -> new ArrayList<>()).add(recipes[i]); |
| 9 | + ingredientCounter.put(recipes[i], ingredientCounter.getOrDefault(recipes[i], 0) + 1); |
12 | 10 | }
|
13 | 11 | }
|
14 |
| - Queue<String> queue = new LinkedList<>(List.of(supplies)); |
15 |
| - Set<String> result = new HashSet<>(); |
| 12 | + Queue<String> queue = new LinkedList<>(); |
| 13 | + Set<String> prepared = new HashSet<>(); |
| 14 | + for (String supply : supplies) { |
| 15 | + queue.add(supply); |
| 16 | + } |
16 | 17 | while (!queue.isEmpty()) {
|
17 |
| - String ingredient = queue.remove(); |
18 |
| - for (String dependentRecipe : ingredientToRecipeMap.getOrDefault(ingredient, |
19 |
| - new HashSet<>())) { |
20 |
| - recipeToIngredientCount.put(dependentRecipe, |
21 |
| - recipeToIngredientCount.get(dependentRecipe) - 1); |
22 |
| - if (recipeToIngredientCount.get(dependentRecipe) == 0) { |
23 |
| - result.add(dependentRecipe); |
| 18 | + String removed = queue.remove(); |
| 19 | + for (String dependentRecipe : map.getOrDefault(removed, new ArrayList<>())) { |
| 20 | + ingredientCounter.put(dependentRecipe, ingredientCounter.getOrDefault(dependentRecipe, 0) - 1); |
| 21 | + if (ingredientCounter.get(dependentRecipe) == 0) { |
24 | 22 | queue.add(dependentRecipe);
|
| 23 | + prepared.add(dependentRecipe); |
25 | 24 | }
|
26 | 25 | }
|
27 | 26 | }
|
28 |
| - return new ArrayList<>(result); |
| 27 | + return new ArrayList<>(prepared); |
29 | 28 | }
|
30 | 29 | }
|
0 commit comments