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

1.LeetCode之Python版本的“两数之和”(简单题)

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

1.LeetCode之Python版本的“两数之和”(简单题)

1.题目描述

2.算法思路

顺序遍历数组,每访问一个数,就用目标数减去这个数,查看减法的结果是否存在于数组中。为了避免返回的结果是自己和自己相加,首先将自己先移除,然后再判断。如果在的话,就输出两个数的下标;如果不在的话,就将刚才移掉的自己再插入到原来的位置上保持不变,访问下一个数。

3.最终提交代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            target1 = nums[i]
            target2 = target-target1
            nums.remove(target1)
            if target2 in nums:
                return [i,nums.index(target2)+1]
            else:
                nums.insert(i,target1)
4.编写验证过程中的完整代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            target1 = nums[i]
            target2 = target-target1
            nums.remove(target1)
            if target2 in nums:
                return [i,nums.index(target2)+1]
            else:
                nums.insert(i,target1)
solution = Solution()
print(solution.twoSum([2,7,11,15], 9))

拒绝内耗,永远心存善念。

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

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

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