Python两数之和

Python两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

思路一:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        i = index_2 = None
        for i in range(0, len(nums)):
            if (target - nums[i]) in nums and ((target - nums[i]) != nums[i] or nums.count(nums[i]) > 1):
                index_2 = nums.index(target - nums[i], i + 1)
                break

        return [i, index_2] if index_2 else []

思路二:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        i = index_2 = None
        for i in range(0, len(nums)):
            if (target - nums[i]) in nums[i + 1:] and ((target - nums[i]) != nums[i] or nums.count(nums[i]) > 1):
                index_2 = nums.index(target - nums[i], i + 1)
                break

        return [i, index_2] if index_2 else []

思路三:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hash_map = {}
        for i, t in enumerate(nums):
            if target - t in hash_map:
                return [hash_map[target - t], i]
            hash_map[t] = i

相关推荐