Getting the maximum number indices in an array

I have an array containing numbers that are ranks.

Something like that:

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

Here it 0corresponds to the lowest rank, and max- to the number of the highest rank. There may be several indexes containing the highest rank.

I want to find the index of all these highest ranks in an array. I have achieved using the 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();
    }
}

I have a result like: 1 6 9

Is there a better way than this?

Because in my case there could be an array containing millions of elements, because of which I have some performance issues.

So,

Any suggestion is appreciated.

+6
source share
3

, . , , no-op. , , . , .

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];
    }
}
+11

... :)

int[] data = { 0, 4, 2, 0, -1, 0, 4, 2, 0, 4, 0, 2 };
int max = Arrays.stream(data).max().getAsInt();
int[] indices = IntStream.range(0, data.length).filter(i -> data[i] == max).toArray();
+3

, 2 . : , . max, , . . : , {1,3,5,3,4,5}, . 1 max, 3, 5, . 5 3 4, 5, max.Hope, .

-1

Source: https://habr.com/ru/post/1017407/


All Articles