Given an array of integers, return indices of the both numbers such that they add-to a specific target.
You may assume this each input would has exactly one solution.
Example:
Given nums = [2, 7, one, 2], target = 9,because nums[0] + nums[1] = + 7 = 9,return [0, 1].
In short, find two numbers within a given array, making two numbers and for a given target
Ideas:
Iterates through the given array, using a hash table to hold the values that have been traversed, key is the value in Nums, and value is its position index.
For the currently traversed Nums[i], look for the existence of target-nums[i in the hash table, or, if present, return both indexes, otherwise (key=nums[i],value=i) into the hash table and continue traversing
Time complexity: O (N)
The Python code is as follows, AC:
1 classsolution (object):2 deftwosum (self, Nums, target):3 """4 : Type Nums:list[int]5 : Type Target:int6 : Rtype:list[int]7 """8Dictmap = {}9 forIndex, valueinchEnumerate (nums):Ten ifTarget-valueinchDictmap: One return[Dictmap[target-value], index] ADictmap[value] = Index
Submit Result:
Leetcode-1-the Sum