我遇到了这个问题我需要在具有最大值的hashmap中返回密钥,这里的技巧是该方法必须考虑边缘情况。我也只能使用上面的导入,所以不允许使用Map.Entry。 Collections.sort不是等等。谢谢。
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class Exercise {
public static String findLargest(HashMap<String, Integer> map) {
// Enter code here
if(that.isEmpty()) return "";
Integer maxInt = Integer.MIN_VALUE;
String maxCity = "";
for(String entry : that.keySet()) {
if (that.get(entry) != null && that.get(entry) < Integer.MAX_VALUE && that.get(entry) > Integer.MIN_VALUE && that.get(entry) > maxInt) {
maxInt = that.get(entry);
maxCity = entry;
}
}
return maxCity;
}
public static void check(String largest, List<String> apples, List<Integer> size) {
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < apples.size(); i++) {
map.put(apples.get(i), size.get(i));
}
assert largest.equals(findLargest(map)) : "expected " + largest + " but was " + findLargest(map);
}
public static void main(String[] arg) {
check("Granny", Arrays.asList("Granny", "Eve", "Rose"), Arrays.asList(5, 1, 2));
}
}
答案 0 :(得分:0)
解决方案效率非常低,但是如果你不能添加任何其他导入......它可以工作。第一步是在整数中找到最大值,然后对每个键,检查map.get(key).equals(max)
:
public static String findLargest(HashMap<String, Integer> map) {
//step 1
int max = Integer.MIN_VALUE;
for (int i : map.values()) {
max = Math.max(max, i);
}
//step 2
for (String str : map.keySet()) {
if (map.get(str).equals(max)) {
return str;
}
}
return null;
}