LeetCode练习(Python):数组类:第1题:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。  你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
思路:本题较为简单,一个元素不能使用两遍,因此只能用一次循环,在一次循环里解决所有问题。
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        i = 0
        while i < len(nums):
            target1 = target - nums[i]
            target2 = nums[i + 1 :]
            if target1 in target2:
                return [i, target2.index(target1) + i + 1]
            i = i + 1
原文地址:https://www.cnblogs.com/zhuozige/p/12718142.html