题目:https://leetcode-cn.com/explore/featured/card/recursion-i/259/complexity-analysis/1227/
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
抄:
递归快速幂
-
时间复杂度:O(log(n))O(log(n))。每次我们应用公式 (x ^ n) ^ 2 = x ^ {2 * n}(xn)2=x2∗n,nn 就减少一半。 因此,我们最多需要 O(log(n))O(log(n)) 次计算来得到结果。
-
空间复杂度:O(log(n))O(log(n))。每次计算,我们都需要存储 x ^ {n / 2}xn/2 的结果。 我们需要计算 O(log(n))O(log(n)) 次,因此空间复杂度为 O(log(n))O(log(n))。
class Solution { public: double fastPow(double x,long long n){ if(n==0) return 1.0; double half = fastPow(x,n/2); if(n%2==0) return half*half; else return half*half*x; } double myPow(double x, int n) { long long N = n; if(N<0) {x = 1 / x; N = -N; } return fastPow(x,N); } };
迭代快速幂
-
时间复杂度:O(log(n))O(log(n))。每次我们应用公式 (x ^ n) ^ 2 = x ^ {2 * n}(xn)2=x2∗n,nn 就减少一半。 因此,我们最多需要 O(log(n))O(log(n)) 次计算来得到结果。
-
空间复杂度:O(log(n))O(log(n))。每次计算,我们都需要存储 x ^ {n / 2}xn/2 的结果。 我们需要计算 O(log(n))O(log(n)) 次,因此空间复杂度为 O(log(n))O(log(n))。
class Solution { public: double myPow(double x, int n) { long long N = n; if (N < 0) { x = 1 / x; N = -N; } double ans = 1; double current_product = x; for (long long i = N; i ; i /= 2) { if ((i % 2) == 1) { ans = ans * current_product; } current_product = current_product * current_product; } return ans; } };