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.
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With