Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting indexes of maximum number in array

I have an array containing numbers which are ranks.

Something like this :

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

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

I have got result as : 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.

So,

Any suggestion is appreciated.

like image 228
Sagar Gautam Avatar asked May 20 '17 09:05

Sagar Gautam


1 Answers

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];
    }
}
like image 177
Tim Biegeleisen Avatar answered Oct 14 '22 05:10

Tim Biegeleisen