[英]Getting two elements from a map which their sum equals to a desired number
I am trying to find a way to get the first 2 elements from a map which their value combined gives me a desired sum.我正在尝试找到一种方法来从 map 中获取前两个元素,它们的值加起来就是我想要的总和。 I was thinking of a solution which combined 2 maps where the key of the second map is the reminder of the target number minus the value of the entry of the first map. I am lost and not sure what I am missing.我在想一个结合了 2 个地图的解决方案,其中第二个 map 的键是目标号码的提醒减去第一个 map 的条目的值。我迷路了,不确定我错过了什么。 What am I missing here?我在这里错过了什么?
the problem you're facing is that the int is the value, not the key.您面临的问题是 int 是值,而不是键。 so pairOfItems.containsKey(remainder)
should not compile.所以pairOfItems.containsKey(remainder)
不应该编译。 luckily for you, Map also has containsValue()
method.幸运的是,Map 也有containsValue()
方法。 as long as there is no requirement for minimum performance, that should solve your problem.只要对最低性能没有要求,就应该可以解决您的问题。
...and you don't need a 2nd map. you can just ask items.containsValue(reminder)
...并且您不需要第二个 map。您可以直接询问items.containsValue(reminder)
I would suggest introducing a new Map remainderToItem
, looping through all relevant items and adding their reminder to the Map as key and item key as the value我建议引入一个新的 Map remainderToItem
,遍历所有相关项目并将它们的提醒添加到 Map 作为键和项目键作为值
then iterate the relevantItems
Map again to find the price is matching with some other reminder Also check remainderToItem.get(entry.getValue()).equals(entry.getKey()))
(in case the value is 50 reminder is also 50) , this prevents adding same item again to itemsThatCanBeBought
然后再次迭代relevantItems
Map 以发现价格与其他一些提醒匹配还要检查remainderToItem.get(entry.getValue()).equals(entry.getKey()))
(如果值为 50 提醒也是 50) , 这可以防止再次将相同的项目添加到itemsThatCanBeBought
private static List<String> getTwoItemsWhichSumTo100(Map<String, Integer> items, int target) {
Map<String, Integer> relevantItems = getRelevantItems(items, target);
Map<Integer, String> remainderToItem = new HashMap<>();
List<String> itemsThatCanBeBought = new ArrayList<>();
for (Map.Entry<String, Integer> entry : relevantItems.entrySet()) {
int remainder = target - entry.getValue();
remainderToItem.put(remainder, entry.getKey());
}
for (Map.Entry<String, Integer> entry : relevantItems.entrySet()) {
if (remainderToItem.containsKey(entry.getValue()) && !remainderToItem.get(entry.getValue()).equals(entry.getKey())) {
itemsThatCanBeBought.add(entry.getKey());
itemsThatCanBeBought.add(remainderToItem.get(entry.getValue()));
return itemsThatCanBeBought;
}
}
return itemsThatCanBeBought;
}
private static Map<String, Integer> getRelevantItems(Map<String, Integer> items, int target) {
Map<String, Integer> relevantItems = new HashMap<>();
for (Map.Entry<String, Integer> entry : items.entrySet()) {
if (entry.getValue() < target) relevantItems.put(entry.getKey(), entry.getValue());
}
return relevantItems;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.