【问题描述】
Implement pow(x, n).
1.【基础知识】
1)分治的意识,一道O(N)的算法题,琢磨出O(lgN)的思想出来就是要求;
2.【屌丝代码】
卡壳的地方:
1.Time Limit Exceeded。
#include <vector>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
// Status: Time Limit Exceeded
class Solution {
public:
double myPow(double x, int n) {
double res(1);
if(n==0)
return 1;
for(int i=0;i<n;i++)
res = res*x;
return res;
}
};
int main()
{
int n=1;
double x = 2.0;
Solution mySln;
double num = mySln.myPow(x, n);
cout<<num<<endl;
while(1);
return 0;
}
3.【源码AC】
//LeetCode, Pow(x, n)
// 二分法, $ x^n = x^{n/2} * x^{n/2} * x^{n\%2} $
// 时间复杂度 O(logn),空间复杂度 O(1)
class Solution {
public:
double myPow(double x, int n) {
if (n < 0)
return 1.0 / power(x, -n);
else
return power(x, n);
}
private:
double power(double x, int n) {
if (n == 0)
return 1;
double v = power(x, n / 2);
if (n % 2 == 0)
return v * v;
else
return v * v * x;
}
};
4.【复盘】
1)卡壳部分
O(N)与O(lgN)的差距;
指数的负数考虑。
2)AC源码思想——二分(分治思想)
二分法: x^n = x^n/2 × x^n/2 × x^n%2