Java中ArrayList中Max值的位置

时间:2014-08-31 01:44:29

标签: java arraylist

有没有找到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);
    }

1 个答案:

答案 0 :(得分: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.

可能有第三方库将其作为库方法提供。


我认为使用一个线程可以更快地完成此操作。如果列表非常大,使用多个线程扫描列表的不同部分可能会提供更好的性能。但是,您具有同步和设置的复杂性/开销。并且实际性能可能受到硬件存储系统的限制;即高速缓存的大小和内存带宽。


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

  • 如果您只在列表的末尾添加元素,并且从不更新或删除元素,那么每次append和元素都可以更新包含最大元素及其位置的变量列表

  • 在更一般的情况下,可能可以设计和实现专门的自定义列表类型,以跟踪面对任何类型更新的最大和最大位置。但是数据结构会很复杂并且内存很耗尽,get之类的操作会从O(1)变为O(logN)或更糟。