栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python7-回文数、两数之和

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python7-回文数、两数之和

1.利用字符串中的pop()方法【双向队列】

    def isPalindrome(x: int):
        lst = list(str(x))
        while len(lst) > 1:
        # 头尾删除,判断是否一致
        # 一致继续判断,否则直接返回False
            if lst.pop(0) != lst.pop():
                return  False
        return True


2.利用字符串索引方式判断【双指针】
    def isPalindrome(x: int) -> bool:
        lst = list(str(x))
        # L,R为字符串的左、右索引
        L, R = 0, len(lst)-1
        while L <= R:
            if lst[L] != lst[R]:
                return  False
            # 当lst[L]等于lst[R]时,左索引值+1,右索引值-1
            L += 1
            R -= 1
        return True

给出一个列表,和一个目标数,找出和为目标值的两个数,返回其索引
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)-1):
            for n in range(len(nums)-1):
                if n>=i:
                    if nums[i]+nums[n+1]!= target:
                        n = n + 1
                    else:
                        return [i,n+1]

if __name__=='__main__':
    a = Solution()
    result = a.twoSum([2,7,11,15],9)
    print(result)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/757856.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号