gpt4 book ai didi

Java:从数组切片中查找最大值的索引

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

我有一个很大的数组。我有一些 Java 代码,用于识别该大数组的子集/切片的起点和终点的索引。我需要从数组的选定子部分检索的唯一信息项是局部最大值和最小值的索引和值。我可以在指定范围内找到最大值和最小值的最快(且占用内存最少)的方法是什么?

这是我需要的代码的开始:

// Step One: declare new array and populate it
pts = new double[5000];
for (int i = 0; i < 5000; i++){ pts[i] = (value assigned by extraneous process);}
// Step Two: slice out section between indices 3600 and 3750
// what code do I write here?
// Step Three: find max value in the sliced section and return its index
// what code to I write here?

最佳答案

只需迭代所需的范围并记录最大和最小可见值:

double max = Double.NEGATIVE_INFINITY;
double min = Double.POSITIVE_INFINITY;
int minIndex = -1;
int maxIndex = -1;
for(int k = 3600; k < 3750; k++){
if(max < pts[k]){
max = pts[k];
maxIndex = k;
}else if(min > pts[k]){
min = pts[k];
minIndex = k;
}
}

关于Java:从数组切片中查找最大值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6605022/

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