leetcode_algorithm1.two_sun

 <h1>环境:</h1>python3

题目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

(给出一个数组和一个整数,找出两个数使得它们的和等于这个整数,并返回这两个的索引)

You may assume that each input would have exactly one solution, and you may not use the same element twice.

(你可以假设的输入只有唯一确定的解,并且不同使用相同的元素两次)

思路:

初看这个题目,似乎很容易,只要对数组进行两次遍历就可以了,但是题目中给出了一个限制,那就是相同的元素不能使用两次。

很自然地就想到了使用字典。假设数组为A=[a1, a2,a3,...an],给出的整数位target,字典的key存储的是target-an,然后只要判断这个key是否存在于数组中就可以了。先给出代码如下:


nums = [-2, -2, -3, -4, -5]
target = -8
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        memory = {}
        for i in range(len(nums)):
            if nums[i] in memory:
                return [memory[nums[i]], i]
            else:
                memory[target - nums[i]] = i
                print(memory)

s = Solution()
t = s.twoSum(nums, target)

print(t)

猜你喜欢

转载自blog.csdn.net/qq_30124241/article/details/87888688