Python 两数之和

两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

1、

class Solution:
    def twoSum(self, nums: List[int], target: int):
        for i in nums:
            j = target - i
            start_index = nums.index(i)
            next_index = start_index + 1
            temp_num = nums[next_index:]
            if j in temp_num:
                return [nums.index(i), next_index + temp_num.index(j)]

2、

class Solution(object):
    def twoSum(self, nums, target):
        # 定义字典
        num_dict = {}
        len_nums = len(nums)
        # 遍历列表
        for i in range(len_nums):
            temp = target - nums[i]
            if temp not in num_dict:
                num_dict[nums[i]] = i
            else:
                return [num_dict[temp], i]

我不生产程序,我只是程序的搬运工

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。