LeetCode 之 Pow(x, n)(分治法)

來源:互聯網
上載者:User

標籤:分治法   二分   leetcode   implement pow   time limit exceeded   

【問題描述】

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 Exceededclass 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源碼思想——二分(分治思想)

二分法: xn = x^n/2 × x^n/2 × x^n%2

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

LeetCode 之 Pow(x, n)(分治法)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.