iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

開學之前....系列 第 14

Day15-1.Two Sum

今日題目:1.Two Sum(Easy)

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]

My solution

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        #n = len(nums)

        d = {}
        for i, n in enumerate(numbers):
            m = target - n
            if m in d:
                return ([d[m], i])
            else:
                d[n] = i

Result

https://ithelp.ithome.com.tw/upload/images/20210924/20140843ApsxUzYnix.png


上一篇
Day14-Machine Learning : Self-attention
下一篇
Day16-205. Isomorphic Strings
系列文
開學之前....20

尚未有邦友留言

立即登入留言