LeetCode50 Pow(x, n)--数组--二分法查找--中等

相关博文:

LeetCode35. 搜索插入位置 --(数组)--二分法查找-- 简单

LeetCode 69. Sqrt(x)--(数组)--二分法查找 --简单

题目描述:

 
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
 
示例 1:
 
输入: 2.00000, 10
输出: 1024.00000
示例 2:
 
输入: 2.10000, 3
输出: 9.26100
示例 3:
 
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
 
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
 

解题思路

1)暴力破解

直接判断 while 循环 n 

x相乘

判断若n为负数的处理方法

这个属于暴力破解可能会超过时间的限制

//C++
class Solution {
    public double myPow(double x, int n) 
    {
        long N = n;
        if (N < 0) 
        {
            x = 1 / x;
            N = -N;
        }
        double ans = 1;
        for (long i = 0; i < N; i++)
            ans = ans * x;
        return ans;
    }
};

算法复杂度分析

2)解法2:快速幂指数,利用了二分的特性 

递归

利用该特性:

但分n为奇数和偶数 

//C++
class Solution {
    private double fastPow(double x, long n) 
    {
        if (n == 0) //最后返回给half 最后1次
        {
            return 1.0;
        }
        double half = fastPow(x, n / 2);// n/2次
        if (n % 2 == 0) 
        {
            return half * half;
        } else 
        {
            return half * half * x;
        }
    }
    public double myPow(double x, int n) 
    {
        long N = n;
        if (N < 0) 
        {
            x = 1 / x;
            N = -N;
        }

        return fastPow(x, N);//1次
    }
};

算法复杂度分析:

时间复杂度和空间复杂度分析:

3)解题思路3 利用循环替代递归

//循环的方法实现
//C++
class Solution {
    public double myPow(double x, int n) {
        long N = n;
        if (N < 0) //考虑幂是否为负数情况
        {
            x = 1 / x;
            N = -N;
        }
        double ans = 1;
        double current_product = x;
        for (long i = N; i > 0; i /= 2) //每次循环减少一半
        {
            if ((i % 2) == 1) //如果为为奇数,首次,那么多乘1次,最后无论奇数偶数最后都会进入此循环
            {
                ans = ans * current_product;
            }
            current_product = current_product * current_product;
        }
        return ans;
    }
};

算法复杂度分析

时间复杂度:O(logN)

空间复杂度:O(1)

参考资料:

【1】https://leetcode-cn.com/problems/powx-n

发布了136 篇原创文章 · 获赞 112 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/heda3/article/details/103947293
今日推荐