获取数组中最大数量的索引 [英] Getting indexes of maximum number in array

查看:51
本文介绍了获取数组中最大数量的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中包含排名。

I have an array containing numbers which are ranks.

这样的事情:

0 4 2 0 1 0 4 2 0 4 0 2

此处 0 对应最低排名 max 数字对应最高排名。可能有多个索引包含最高排名。

Here 0 corresponds to the lowest rank and max number corresponds to highest rank. There may be multiple indexes containing highest rank.

我想找到数组中所有最高排名的索引。我用以下代码实现了:

I want to find index of all those highest rank in array. I have achieved with following code:

import java.util.*;

class Index{

    public static void main(String[] args){

        int[] data = {0,4,2,0,1,0,4,2,0,4,0,2};
        int max = Arrays.stream(data).max().getAsInt();
        ArrayList<Integer> indexes = new ArrayList<Integer>();

        for(int i=0;i<12;i++){
            if(data[i]==max){
               indexes.add(i);
            }
        }

        for(int j=0;j<indexes.size();j++){
            System.out.print(indexes.get(j)+" ");   
        }
        System.out.println();
    }
}

我的结果为: 1 6 9

有没有比这更好的方法?

Is there any better way than this ?

因为,在我的情况下,可能有一个包含数百万个元素的数组,因此我对性能有一些问题。

Because, In my case there may be an array containing millions of elements due to which I have some issue regarding performance.

所以,

任何建议都表示赞赏。

推荐答案

一种方法是简单地沿阵列进行单次传递并跟踪最高数量的所有索引。如果当前条目小于目前为止看到的最高数字,那么no-op。如果当前条目与看到的最大数字相同,则添加该索引。否则,我们已经看到了一个新的最高数字,我们应该扔掉我们最旧的最高数字列表并开始一个新的数字。

One approach would be to simply make a single pass along the array and keep track of all indices of the highest number. If the current entry be less than the highest number seen so far, then no-op. If the current entry be the same as the highest number seen, then add that index. Otherwise, we have seen a new highest number and we should throw out our old list of highest numbers and start a new one.

int[] data = {0,4,2,0,1,0,4,2,0,4,0,2};
int max = Integer.MIN_VALUE;
List<Integer> vals = new ArrayList<>();

for (int i=0; i < data.length; ++i) {
    if (data[i] == max) {
        vals.add(i);
    }
    else if (data[i] > max) {
        vals.clear();
        vals.add(i);
        max = data[i];
    }
}

这篇关于获取数组中最大数量的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆