Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.php
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.ios
Note:微信
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
複製代碼
Example:less
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
複製代碼
根據字典的特性,在遍歷 numbers 的時候,查看是否有符合結果的兩個數字,有的話直接返回索引結果,不然就將其加入字典中,時間複雜度爲 O(N),空間複雜度爲 O(N)。yii
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in range(len(numbers)):
if target - numbers[i] in d:
return [ d[target - numbers[i]],i+1 ]
elif numbers[i] not in d:
d[numbers[i]] = i+1
複製代碼
Runtime: 48 ms, faster than 81.07% of Python online submissions for Two Sum II - Input array is sorted.
Memory Usage: 12.5 MB, less than 7.71% of Python online submissions for Two Sum II - Input array is sorted.
複製代碼
每日格言:過去屬於死神,將來屬於你本身。svg