LeetCode 之 Pow(x, n)(分治法)
阿新 • • 發佈:2019-02-01
【問題描述】
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