Reputation: 824
I would like to find the index/indices that hold the maximum value in an ArrayList
. I want to preserve the order that the numbers are in (in other words no sorting) because I want to keep track of what index had what value. The values are from a random number generator and there is the possibility of having two (or more) indices sharing the same maximum value.
An example ArrayList
:
12, 78, 45, 78
0,1,2,3 <- indices
(So indices, 1 and 3 contain the values that have the max values. I want to maintain the fact that indices 1 and 3 have the value 78. I do not want to just create a new ArrayList
and have indices 0 and 1 of the new ArrayList
have the values 78)
Therefore, I want to find all of the indices that have the maximum values because I will be doing something with them to "break" the tie if there is more than one index. So how can I find the indices that contain the maximum value and maintain the index-to-value relationship?
I have written the following methods:
public static ArrayList<Integer> maxIndices(ArrayList<Integer> numArrayList) {
// ???
return numArrayList;
}
public static void removeElement(ArrayList<Integer> numArrayList, int index) {
numArrayList.remove(index);
}
public static int getMaxValue(ArrayList<Integer> numArrayList) {
int maxValue = Collections.max(numArrayList);
return maxValue;
}
public static int getIndexOfMaxValue(ArrayList<Integer> numArrayList, int maxVal) {
int index = numArrayList.indexOf(maxVal);
return index;
}
Upvotes: 2
Views: 6845
Reputation: 32004
O(n) solution:
public static List<Integer> maxIndices(List<Integer> l) {
List<Integer> result = new ArrayList<Integer>();
Integer candidate = l.get(0);
result.add(0);
for (int i = 1; i < l.size(); i++) {
if (l.get(i).compareTo(candidate) > 0) {
candidate = l.get(i);
result.clear();
result.add(i);
} else if (l.get(i).compareTo(candidate) == 0) {
result.add(i);
}
}
return result;
}
Upvotes: 1
Reputation: 925
public static ArrayList<Integer> maxIndices(ArrayList<Integer> list) {
List<Integer> indices = new ArrayList<Integer>();
int max = getMaxValue(list);
for (int i = 0; i < list.size(); i++) {
if(list.get(i) == max) {
indices.add(list.get(i));
}
}
return indices;
}
Upvotes: 3