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

时间:2011-07-07 01:56:28

标签: java arrays max slice min

我有一个大阵列。我有一些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?

4 个答案:

答案 0 :(得分:4)

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

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;
    }
}

答案 1 :(得分:3)

如果没有必要为切片创建数组的副本,您基本上可以一步完成第2步和第3步:

double max = pts[3600]; //the value of the first element in the slice
int maxIndex = 3600; //keep track of the index as you go. Assume at first
                     //that it is the first index of the slice
for(int i=3601; i<=3750; i++){
  if(pts[i] > max){  //you have encountered a larger element. Update the maxes
    max = pts[i];
    maxIndex = i;
  }
}
System.out.println("The max is " + max + " and occurred at index " + maxIndex);

(抱歉任何语法错误,我一直在搞乱Scala,语法有点不同)

答案 2 :(得分:1)

有一个循环遍历选定的子部分。

在循环中,当您找到新的最大值或最小值时,调整四个变量maxValuemaxIndexminValueminIndex的值。

在循环之后,您将获得最大值和最小值以及它们的位置。

不需要额外的内存,线性性能(只需对阵列的选定部分进行一次传递)。

答案 3 :(得分:1)

如果您要做很​​多事情,可以通过跟踪不同比例的最大值/最小值来提高性能。

例如,如果你每20行保留一个列表,并且你想要检查范围55-184,你只需要检查5个值(55-59),然后检查6个值60-179,然后4个值从180到184,所以15次检查而不是130次,速度增加20倍。

当然,您需要在数组更改时将存储桶标记为已更改,并定期更新它们。

相关问题