Created
May 17, 2017 15:47
-
-
Save anil477/d7410c21e61cdf7fc7479d6a09493bac to your computer and use it in GitHub Desktop.
Write a function fib() that a takes an integer n, and returns the nth fibonacci number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// N time and O(1)O(1) space | |
import java.util.Map; | |
import java.util.HashMap; | |
class Fibber { | |
Map<Integer, Integer> memo = new HashMap<Integer, Integer>(); | |
public int fib(int n) { | |
// edge case: negative index | |
if (n < 0) { | |
throw new IllegalArgumentException("Index was negative. No such thing as a negative index in a series."); | |
} | |
// base case: 0 or 1 | |
else if (n == 0 || n == 1) { | |
return n; | |
} | |
// see if we've already calculated this | |
if (memo.containsKey(n)) { | |
return memo.get(n); | |
} | |
int result = fib(n-1) + fib(n-2); | |
// memoize | |
memo.put(n, result); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment