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

【问题描述】

Implement pow(xn).

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值