I was asked to implement a Fibonacci program that can be reused again. I used a Hashmap below. Just curious, if I should have actually implemented a TreeMap to help performance? I was looking through resources and keep reading that Hashmap is better for performance, Treemap is for iterating and memory saving. What would be the ideal data structure, or does it matter?
public class Fibonacci {
HashMap<Integer, Integer> map = new HashMap<>() {{
map.put(0, 0);
map.put(1, 1);
}};
int currentMax = 1;
public int getFibonacci(int newIndex) {
if (newIndex > currentMax) {
for (int i = currentMax + 1; i <= newIndex; i++) {
int newData = map.get(i - 1) + map.get(i - 2);
map.put(i, newData);
}
currentMax = newIndex;
}
return map.get(newIndex);
}
}
Note: I do not know how big the hashmap will be, as program can be used multiple times.
int[]as cache instead.System::arraycopy(docs.oracle.com) is for.O(log(n)).