LeetCode【第1題】Two Sum

3336 ワード

LeetCodeをブラシするつもりです.
タイトル:
'''
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.

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

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

中国語タイトル:
'''
        ,         ,                  target。

                  。

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

  nums [0] + nums [1] = 2 + 7 = 9,
return [0,1]。
'''

解法1とメモ:
 1 class Solution(object):
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         arr = {}                       #        
 9         length = len(nums)
10         for i in range(length):
11             if (target - nums[i]) in arr:     #   target                 ,    。
12                 return [arr[target - nums[i]], i]  #   target-nums[i] i   
13             arr[nums[i]] = i                   #           arr
14 
15 #    accepted ,           
16 a = Solution().twoSum([3, 2, 4], 6)
17 print(a)