mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 01:35:16 +08:00
Merge pull request #649 from shoaibrayeen/patch-1
Optimized Version [Without Hashmap & recursion]
This commit is contained in:
@ -29,6 +29,10 @@ public class Fibonacci {
|
||||
* Outputs the nth fibonacci number
|
||||
**/
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private static int fibMemo(int n) {
|
||||
if (map.containsKey(n)) {
|
||||
return map.get(n);
|
||||
@ -71,5 +75,35 @@ public class Fibonacci {
|
||||
|
||||
return fib.get(n);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* This method finds the nth fibonacci number using bottom up
|
||||
*
|
||||
* @author Shoaib Rayeen (https://github.com/shoaibrayeen)
|
||||
* @param n The input n for which we have to determine the fibonacci number
|
||||
* Outputs the nth fibonacci number
|
||||
*
|
||||
* This is optimized version of Fibonacci Program. Without using Hashmap and recursion.
|
||||
* It saves both memory and time.
|
||||
* Space Complexity will be O(1)
|
||||
* Time Complexity will be O(n)
|
||||
*
|
||||
* Whereas , the above functions will take O(n) Space.
|
||||
**/
|
||||
private static int fibOptimized(int n) {
|
||||
|
||||
if (n == 0) {
|
||||
return 0;
|
||||
}
|
||||
int prev = 0 , res = 1 , next;
|
||||
for ( int i = 2; i < n; i++) {
|
||||
next = prev + res;
|
||||
prev = res;
|
||||
res = next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user