跟着专注于计算机视觉的AndyJ的妈妈我学算法之每日一题leetcode372超级次方

这种题还是挺常考的,尤其是觉得手撕代码的时候,毕竟手撕代码更过关注的是优化。时间复杂度或者是空间复杂度。
赶快先写了下快速幂,代码如下:

def fastmi(num, a):
    res = 1
    while a:
        if a%2 == 0:
            num *= num
            a = a//2
        else:
            res *= num
            a -= 1
    return res

res = fastmi(2,10)

好了,来进入正题,看题:

372. 超级次方
你的任务是计算 ab 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。

示例 1:

输入: a = 2, b = [3]
输出: 8
示例 2:

输入: a = 2, b = [1,0]
输出: 1024

其实是个回溯的题。公式如下:
a [ 1 , 2 , 3 , 4 ] = a 4 × a [ 1 , 2 , 3 , 0 ] = a 4 × ( a [ 1 , 2 , 3 ] ) 10 a^{[1,2,3,4]} = a^{4} \times a^{[1,2,3,0]} = a^{4} \times (a^{[1,2,3]})^{10}
这样接着对 a [ 1 , 2 , 3 ] a^{[1,2,3]} 计算结果。
好了,不如看代码:

class Solution:
    def superPow(self, a: int, b: List[int]) -> int:
        if not b: return 1

        n = b.pop()
        part1 = self.fastmi(a, n) % 1337
        part2 = self.fastmi(self.superPow(a, b), 10) % 1337
        return (part1*part2) % 1337

    def fastmi(self, num, a):
        res = 1
        while a:
            if a%2 == 0:
                num *= num
                a = a//2
            else:
                res *= num
                res = res%1337
                a -= 1
        return res

具体详细的东西,可以参考leetcode题解
好了,开动脑筋,好好写题吧。

猜你喜欢

转载自blog.csdn.net/mianjiong2855/article/details/106993058
今日推荐