LeetCode之1. Two Sum

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


找出一个数组中相加为目标值的元素的索引, 用字典实现

遍历字典,有配对的数则返回索引,没用则继续寻找

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

结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/github_34777264/article/details/80750129