Two sum(给定一个无重复数组和目标值,查找数组中和为目标值的两个数,并输出其下标)

示例:

nums = [1,2,5,7] target = [6]

return [0,2]

Python解决方案1:

    def twoSum(nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            remain = target - nums[i]
            if remain in nums and nums.index(remain) != i:
                return [i,nums.index(remain)]

Python解决方案2(转载于leetcode用户Dirk41):

    def twoSum(nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        data = { nums[i]: i for i,n in enumerate(nums)}

        for i in range(len(nums)):
            complement = target - nums[i]
            if complement in data and data.get(complement) != i:
                return [i, data.get(complement)]

方案2的运行速度快很多倍

原文地址:https://www.cnblogs.com/wenqinchao/p/10523148.html