“两数之和(Two Sum)”问题的 Python3 解答

题目描述

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解题思路

要求的结果是两个索引组成的 List:[aIndex, bIndex],这两个索引对应的值记为 a, b。

遍历列表,假设列表中第1项的值 a 是结果 List 中的一个索引的值,那么用 target 减去 a 后得到的结果 b 就是就是要找的另一个索引的值,列表除掉 a 后的子列表里面,如果 b 存在,问题已解——答案是 a 的索引和 b 的索引组成的列表 [aIndex, bIndex]。

如果不存在,将列表的第二项赋值给 a,继续寻找 b,直到找到为止。

解答

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        i = 0

        for num in nums:
            nextNum = target - num
            j = i + 1
            if nextNum in nums[j:]:
                return [i, nums[j:].index(nextNum) + i + 1]
            i += 1

中文官网的题目地址:两数之和


评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注