leetcode题python答案汇总之一_数学

本文深入解析了LeetCode上的多个经典算法题目,包括字符串转换整数、整数转罗马数字、罗马数字转整数、字符串相乘、Pow(x,n)、第k个排列、Excel表列名称和求质数等,提供了详细的代码实现和技巧指导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode8. 字符串转换整数 (atoi)

提示: 字符串操作,首选正则,其他方式筛不干净!!强大的正则,把正负号筛选也写进去。

import re
class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str_list=re.findall('^[\+\-]?\d+', str.lstrip())    #去除左侧空格,筛选以+-或数字开头的子串
        if len(str_list)==0: return 0
        str1=str_list[0]
        raw=int(str1)
        if raw>(1<<31)-1: return (1<<31)-1
        if raw<-1*(1<<31): return -1*(1<<31)
        return raw

leetcode12. 整数转罗马数字

提示: 贪心算法,哈希表对应

class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
        romans = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
        roman_nlis=[]
        for n in nums:
            if num>0:
                i, num = divmod(num, n)     #i是每一个roman对应的次数
                roman_nlis.append(i)
        res=''
        for i, r in zip(roman_nlis, romans):
            res+= i*r
        return res

leetcode13. 罗马数字转整数

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {
            "I":1,
            "V":5,
            "X":10,
            "L":50,
            "C":100,
            "D":500,
            "M":1000
        }
        ans=0
        for i, char in enumerate(s[:-1]):
            if dic[char]>=dic[s[i+1]]:     #与下一个字符比较,大则加,小则减
                ans+=dic[char]             # IV(-1+5)  XL(-10+50)  CM(-100+1000)
            else:
                ans-=dic[char]
        ans+=dic[s[-1]]
        return ans

leetcode43. 字符串相乘

提示: 倒序相乘法

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        rnum1=num1[::-1]
        rnum2=num2[::-1]
        ans=0
        for i, n1 in enumerate(rnum1):           #i, j正是对应数字的10的指数
            for j, n2 in enumerate(rnum2):
                ans += int(n1)*int(n2)*10**(i+j)
        return str(ans)

leetcode50. Pow(x, n)

提示: 递归,指数负转正,奇转偶,底数不断减半递归至1

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        if n==0: return 1
        if n>0: return self.repow(x, n)
        if n<0: return 1/self.repow(x, -n)

    def repow(self, x, n):
        if n==1: return x
        if n%2==0: return self.repow(x*x, n/2)
        if n%2==1: return self.repow(x, n-1)*x

leetcode60. 第k个排列

提示: 直接找数学规律。本体不适合回溯,相当麻烦,回溯适合用来找满足某一条件的所有路径,比如Sum Len达到多少,本体直接找规律

class Solution(object):
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """    
        def factoria(n):
            if n==0 or n==1: return 1
            res=1
            while n>1:
                res *= n
                n -= 1
            return res
        nums=[i+1 for i in range(n)]
        res=[]
        while len(nums)>1:
            a, k = divmod(k, factoria(len(nums)-1))
            if k==0:
                a -= 1
                k = factoria(len(nums)-1)
            # print(nums, a)
            res.append(nums[a])
            nums=nums[:a]+nums[a+1:]
        res.append(nums[0])
        # print(res)
        return ''.join([str(i) for i in res])
      
s60 = Solution()
s60.getPermutation(4, 9)

leetcode168. Excel表列名称

提示: 注意正好整除的情况

class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        res=''
        while n>0:
            n, a =divmod(n, 26)   
            if a==0:                #注意正好整除的情况
                n-=1
                a+=26
            res=chr(64+a)+res       #后除的数往前放;chr(65)=='A'
        return res

leetcode204求质数

提示: table筛选,质数的倍数和平方置为0。 不算难,但也不容一次写对。

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n<2: return 0
        lookup = [1]*n
        lookup[0]=lookup[1]=0
        for i in range(2, int(n**0.5)+1):    # 定好j的范围,再定i的范围
            if lookup[i]:
                for j in range(i*i, n, i):   # i*i, n, i(每隔i置为0)
                    lookup[j] = 0
#         print(lookup)
        return sum(lookup)
    
s204 = Solution()
s204.countPrimes(100)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值