Java中ArrayList中最大值的位置

Java中ArrayList中最大值的位置,java,arraylist,Java,Arraylist,有没有什么有效的方法可以找到ArrayList中最大值的位置?我已经写了下面的代码,想知道是否有可能使下面代码中的第2行更高效 static int getPatternCount(ArrayList<Integer> indicesInPool, int indexofEndStr) { int position = indicesInPool.indexOf(Collections.max(indicesInPool)); return (Math

有没有什么有效的方法可以找到ArrayList中最大值的位置?我已经写了下面的代码,想知道是否有可能使下面代码中的第2行更高效

static int getPatternCount(ArrayList<Integer> indicesInPool, int indexofEndStr) {
        int position = indicesInPool.indexOf(Collections.max(indicesInPool));
        return (Math.abs(indexofEndStr - indicesInPool.get(position)) + 1);
    }
静态int-getPatternCount(ArrayList指示InPOOL,int-indexofEndStr){
int position=indicesInPool.indexOf(Collections.max(indicesInPool));
返回值(Math.abs(indexofEndStr-indicesInPool.get(position))+1);
}

第二行将迭代列表两次

通过编写查找最大值并跟踪其发生位置的循环(手动),可以获得更好的性能

ArrayList<Integer> list = ...
int limit = list.size();
int max = Integer.MIN_VALUE;
int maxPos = -1;
for (int i = 0; i < limit; i++) {
    int value = list.get(i);
    if (value > max) {
        max = value;
        maxPos = i;
    }
}
// maxpos now contains the (first) index of the largest value ...
// ... or -1 if the list is empty.
ArrayList=。。。
int limit=list.size();
int max=整数的最小值;
int maxPos=-1;
对于(int i=0;i最大值){
最大值=最大值;
maxPos=i;
}
}
//maxpos现在包含最大值的(第一个)索引。。。
// ... 如果列表为空,则为-1。
可能有第三方库将此作为库方法提供


我认为用一个线程没有更快的方法。如果列表非常大,使用多个线程扫描列表的不同部分可能会提高性能。但是,同步和设置会带来复杂性/开销。实际性能可能受到硬件存储系统的限制;i、 e.缓存大小和内存带宽


根据列表的使用方式,您可以通过其他方式更有效地跟踪最大值及其位置

  • 如果只在列表末尾添加元素,而从不更新或删除元素,则可以在每次向列表添加
    和元素时更新包含最大元素及其位置的变量

  • 在更一般的情况下,可以设计和实现一种专门的自定义列表类型,以便在任何类型的更新中跟踪最大和最大位置。但是,数据结构将非常复杂,并且内存非常紧张,像
    get
    这样的操作将从
    O(1)
    变为
    O(logN)
    甚至更糟


看起来不错。你可以试着问一下。每次你添加到ArrayList时,你都会计算值并创建一个最高的变量。我可以问一下你为什么想要最大值的位置吗?可能还有另一种数据结构更适合您的目的。