gpt4 book ai didi

java - 如何使用java中的TreeMap计算数组右侧较小的元素?

转载 作者:行者123 更新时间:2023-11-30 06:01:18 25 4
gpt4 key购买 nike

我尝试实现这个,但它显示 nullPointerException:它的基本作用是使用 lowerKey() 方法找到第一个低于 A[i] 的元素,然后找到上面找到的元素与 map 开头之间的距离。

 public static void main(String...aks){
Integer arr[] = {12, 1, 2, 3, 0, 11, 4 };

TreeMap<Integer, Integer> treeMap=new TreeMap<Integer, Integer>();
int[] count=new int[arr.length];
for (int i=arr.length-1;i>=0;i--){
treeMap.put(arr[i], 1);
}

for (int j=arr.length-1;j>=0;j--) {
int lowerKey = treeMap.lowerKey(arr[j]);
count[j] = treeMap.headMap(lowerKey).size();
}
for(int elem: count) {
System.out.println(elem);
}

最佳答案

lowerKey 的文档:

Returns the greatest key strictly less than the given key, or null if there is no such key.

这意味着它将为数组的最小值返回null,因此在调用headMap时失败,因为根据headMap的文档:

NullPointerException - if toKey is null and this map uses natural ordering, or its comparator does not permit null keys

关于java - 如何使用java中的TreeMap计算数组右侧较小的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52248064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com