gpt4 book ai didi

java - 高效获取Java 2D数组的row.max和row.sum

转载 作者:行者123 更新时间:2023-12-02 12:46:25 24 4
gpt4 key购买 nike

在Java中,给定一个二维 double 组,其尺寸为6000*6000,是否有一种有效的方法来查询行最大值和行总和?

我使用数据结构 double[][] 和两层循环来获取行 max 和 sum,但效率不够高,因为该函数被频繁调用。

double MinRowMax = Double.POSITIVE_INFINITY;
int num = 6000;
double[][] array2DDist = new double[num][num];
Random rand = new Random();

// initialising the array2DDist
for(int i=0;i<num;++i)
for(int j=0;j<num;++j)
array2DDist[i][j] = rand.nextDouble();

// get the row.max and row.sum
for(int i=0;i<num;++i) {
double maxDist = Double.NEGATIVE_INFINITY;
double sumDist = 0;
for(int j=0;j<num;++j) {
double dist = array2DDist[i][j];
maxDist = Double.max(maxDist, dist);
sumDist+=dist;
}
if(maxDist < MinRowMax) {
MinRowMax = maxDist;
}
}

是否有任何 Java 库可以提供更高效的解决方案?有没有类似于Python或R中的Matrix类的Java库?

谢谢!

最佳答案

计算数组的总和或数组中的最大值,您必须访问数组的每个元素。你无法加快速度。

但是,如果数组不会更改,并且您需要多次求数组的总和和最大值,那么您可以计算它们一次,然后查找它们。有两种方法:

  • 从一开始就计算二维数组所有行所需的值,并将它们存储在查找表中。这是一个表单或eager缓存。

  • 使用(例如)HashMap<Integer, CacheEntry> (其中 CacheEntry 表示总和和最大值),然后使用它来延迟缓存每行所需的值(由键索引)。

(或者上述实现的一些变体。)

<小时/>

Is there any Java library that provides more efficient solutions? Is there any Java library that is similar to Matrix class in Python or R?

据我所知。当然,标准 Java 类库中没有。

但是,如果您使用eagerlazy缓存,则不需要库......来解决此问题。

关于java - 高效获取Java 2D数组的row.max和row.sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44758332/

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