【LeetCode】50_Pow(x, n)

题目

Pow(x, n)

Implement pow(xn).






解析

题目看似很简单,需要注意的地方在于,要考虑到n为负数和0的情况。第二,不能使用递归,要用迭代,递归会导致堆栈溢出。

如果你以为这样就好了,例如我的如下代码

class Solution {
public:
	double myPowSub(double x, int n)
	{
		double ret = 1;
		for(int i = 0; i<n; i++)
		{
			ret *= x;
		}
		return ret;
	}

    double myPow(double x, int n) {
      if (n>=0)
		{
			return myPowSub(x,n);
		}
		else
		{
			return 1.0/myPowSub(x,-n);
		}
    }
};

你会发现凶残的超时了。

0.00001, 2147483647 这个会报错

这个时候就要思考如何改善性能了,例如二分法,把O(n)的时间复杂度降低为O(logn)

关键的是重复的计算就不要进行了,例如x *x可以保存成一个值。

代码如下

class Solution {
public:
	double myPowSub(double x, int n)
	{
		if (n == 0)
		{
			return 1;
		}
		if (n == 1)
		{
			return x;
		}
		if (n%2 == 0)
		{
			double tmp = myPowSub(x,n/2);
			return tmp*tmp;
		}
		else
		{
			double tmp = myPowSub(x,n/2);
			return tmp*tmp*x;
		}
	}

    double myPow(double x, int n) {
      <span style="white-space:pre">		</span>if (n>0)
		{
			return myPowSub(x,n);
		}
		else
		{
			return 1.0/myPowSub(x,-n);
		}
    }
};

大神的思路跟我差不多,不过确实优化了一些,更简洁了

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;
    }
};











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值