1. 程式人生 > >Leetcode 1. Two Sum (Easy)

Leetcode 1. Two Sum (Easy)

[1] get add each cte ger ber amp desc

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.

Example:

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

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

Solution

每遍歷一個nums[i],判斷target - nums[i]是否在nums中。
這裏用到dict(即tmp_num)來存儲nums中每一個值及其對應index。

Notice

應該先判斷target - nums[i]是否在tmp_num中,
再將nums[i]添加到tmp_num中,
否則若先將nums[i]添加到tmp_num,
則判斷target - nums[i]時會將剛添加的nums[i]本身也算上。
錯例:
input: [3, 2, 4] 6
output: [0, 0]
expected: [1, 2]
這裏就是將剛添加的元素3算入了,應該先判斷6 - 3是否在,再添加nums[0]。

Code

 1 class Solution:
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         tmp_num = {}
 9         for i in range(len(nums)):
10             if target - nums[i] in tmp_num:
11                 return
(tmp_num[target - nums[i]], i) 12 else: 13 tmp_num[nums[i]] = i; 14 return (-1, -1)

Beats: 46.65%
Runtime: 56ms

Leetcode 1. Two Sum (Easy)