TwoSum

Description:

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.

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

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

==================================================

The idea is to search target -num in the given nums.  

Since the task assumes that each input would have exactly one solution, means that there is one and only one solution to get the specific target. 

_ver2 is better, it searches the target-num in the saved lookup dictionary when saving the num in the lookup dictionary one by one. This method could save the space and also prevent the index overwriting when there are two same values in the nums. 

""" Implement the search by list.count and index"""

def twoSum_ver1(self,nums,target):
  for cnt,num in enumerate(nums):
    if nums.count(target-num) >0 and nums.index(target-num)!=cnt:
      return [cnt,nums.index(target-num)]

def twoSum_ver3(self,nums,target):
  lookup = {}
  for cnt, num in enumerate(nums):
    if target - num in lookup:
      return [lookup[target-num],cnt]
  lookup[num] = cnt

原文地址:https://www.cnblogs.com/szzshi/p/6945167.html