我想比较2个hashmap,以便对它们之间的任何公共键的值求和hashmap<integer,integer>map1 hashmap<integer,integer>map2最有效的方法是什么
taor4pac1#
获取两个Map的键集( O(n) ).计算它们之间的交集( O(n) ).对于上述集合中的公共键,从两个Map中获取值并求和( O(n) ).总时间复杂度- O(n) .
O(n)
Set<Integer> commonKeys = new HashSet<>(map1.keySet()); commonKeys.retainAll(map2.keySet()); Map<Integer, Integer> result = commonKeys.stream() .collect(Collectors.toMap(Function.identity(), k -> map1.get(k) + map2.get(k)));
1条答案
按热度按时间taor4pac1#
获取两个Map的键集(
O(n)
).计算它们之间的交集(
O(n)
).对于上述集合中的公共键,从两个Map中获取值并求和(
O(n)
).总时间复杂度-
O(n)
.