美文网首页
LeetCode - Two Sum

LeetCode - Two Sum

作者: Jansid | 来源:发表于2017-11-23 22:47 被阅读18次

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].

分析: 从题目可以看出最多只能遍历一遍数组。那么在遍历数组的时候需要记录第一个符合条件的值的下标,并记录下一个要获取的值。因此,在遇到第一个符合条件的值时,需要记录两个值。这个时候就可以使用字典来进行存储了。

def two_sum(nums, target):
    if len(nums) <= 1: return False
    temp_dict = {}  # 用于存第一个值的下下标和需要的值
    for i in range(len(nums)):  # 以下标遍历列表
        # 如果当前位置的值在字典中,那么说明之前已经获取到了一个值
        # 这时直接返回结果 之前保存的下标和当前下标
        if nums[i] in temp_dict:  
            return [temp_dict[nums[i]], i]
        else:  # 如果不在字典中,则把需要的值作为键,下标作为值存在字典中
            nums[target - nums[i]] = i 

相关文章

网友评论

      本文标题:LeetCode - Two Sum

      本文链接:https://www.haomeiwen.com/subject/gvvtbxtx.html