This is a small algorithm within a larger leetcode question. If given an array, say [5,7,3,5,3,5,16,9]
, I want my code to return the location of the three biggest numbers of the array in order. With the mentioned array, the three biggest numbers would be 7, 16, and 9 with respect to their order from left to right. Thus, the method should return [1,6,7]
, or the indices where the three numbers are located.
I've been thinking through this for quite a while now, but I'm not sure how to do it. I've considered implementing HashMaps into the code to set a distinction between array value and location, but am not sure how to implement such a design. Any help would be appreciated, thank you!
EDIT
I found a solution to the problem. FindBig3 uses HashMap to keep a record of both the indexes in the given array and the value within it.
The code goes through the array from left to right with a for loop, and uses the following instructions
- start with the first three array values as being "the big 3", stored within the
lo3
Hashmap - find the smallest value within "the big 3" (uses
findLeastValue
method) - check if the i value in the for-loop is greater than the smallest value within "the big three", if so, then the smallest value is removed from
lo3
and the i value is inserted.
The program then outputs the locations of the 3 biggest numbers (the key set of lo3
)
public static String findBig3(ArrayList<Integer> array) {
HashMap<Integer, Integer> lo3 = new HashMap<Integer, Integer>();
lo3.put(0, array.get(0));
lo3.put(1, array.get(1));
lo3.put(2, array.get(2));
for (int i = 3; i < array.size(); i++) {
int leastLoc = findLeastValue(lo3);
if (array.get(i) > lo3.get(leastLoc)) {
lo3.put(i, array.get(i));
lo3.remove(leastLoc);
}
}
String loc = "";
for (Integer location : lo3.keySet()) {
loc += location + " ";
}
return loc;
}
//returns the KEY with the smallest number
public static int findLeastValue(HashMap<Integer,Integer> lo3) {
int least = Integer.MAX_VALUE;
int leastLoc = 0;
for (Integer key : lo3.keySet()) {
if (lo3.get(key) < least) {
least = lo3.get(key);
leastLoc = key;
}
}
return leastLoc;
}