欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode-1. 两数之和

程序员文章站 2024-03-04 09:12:05
...

1. 两数之和


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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解题思路:最简单的想法是从前到后将数组中的元素两两验证,这需要两层循环。我们使用一个字典new_target{new:i}来记录某个元素与new之和为target与该元素对应的位置i。只要后面元素出现在该字典中,那么[new_target[nums[i],i]即为答案。

Python3代码如下:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        new_target = {}
        for i in range(len(nums)):
            if nums[i] in new_target:
                return [new_target[nums[i]],i]
            else:
                new_target[target-nums[i]] = i

LeetCode-1. 两数之和

相关标签: Easy