LeetCode: Two Sum

topic:

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

Solutions:
1  # Method a: The difference value is stored as the key dict, value of the corresponding index nums, traversed in order to record values, to avoid violent solution 
2  class Solution:
 . 3      DEF twoSum (Self, nums: List [ int], target: int) -> List [int]:
 . 4          _dict = {}
 . 5          for I in Range (len (the nums)):
 . 6              remainning = target - the nums [I]
 . 7              IF remainning in _dict:
 . 8                  return _dict [ remainning], I
 . 9              _dict [the nums [I]] = I
 10                 
# Method Two: Use enumerate the nums into dict, and a method of empathy 
class Solution:
     DEF twoSum (Self, nums, target):
         "" " 
        : nums of the type: List [int] 
        : target of the type: int 
        : rtype: List [ int] 
        "" " 
        H = {}
         for I, NUM in the enumerate (the nums): 
            n- = target - NUM
             IF n- Not  in H: 
                H [NUM] = I
             the else :
                 return [H [n-], I]

 


Guess you like

Origin www.cnblogs.com/noodleman/p/11830589.html