相關博文:
LeetCode35. 搜索插入位置 --(數組)--二分法查找-- 簡單
LeetCode 69. Sqrt(x)--(數組)--二分法查找 --簡單
題目描述:
解題思路
1)暴力破解
直接判斷 while 循環 n
x相乘
判斷若n爲負數的處理方法
這個屬於暴力破解可能會超過時間的限制
//C++
class Solution {
public double myPow(double x, int n)
{
long N = n;
if (N < 0)
{
x = 1 / x;
N = -N;
}
double ans = 1;
for (long i = 0; i < N; i++)
ans = ans * x;
return ans;
}
};
算法複雜度分析
2)解法2:快速冪指數,利用了二分的特性
遞歸
利用該特性:
但分n爲奇數和偶數
//C++
class Solution {
private double fastPow(double x, long n)
{
if (n == 0) //最後返回給half 最後1次
{
return 1.0;
}
double half = fastPow(x, n / 2);// n/2次
if (n % 2 == 0)
{
return half * half;
} else
{
return half * half * x;
}
}
public double myPow(double x, int n)
{
long N = n;
if (N < 0)
{
x = 1 / x;
N = -N;
}
return fastPow(x, N);//1次
}
};
算法複雜度分析:
時間複雜度和空間複雜度分析:
3)解題思路3 利用循環替代遞歸
//循環的方法實現
//C++
class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) //考慮冪是否爲負數情況
{
x = 1 / x;
N = -N;
}
double ans = 1;
double current_product = x;
for (long i = N; i > 0; i /= 2) //每次循環減少一半
{
if ((i % 2) == 1) //如果爲爲奇數,首次,那麼多乘1次,最後無論奇數偶數最後都會進入此循環
{
ans = ans * current_product;
}
current_product = current_product * current_product;
}
return ans;
}
};
算法複雜度分析
時間複雜度:O(logN)
空間複雜度:O(1)
參考資料: