给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
hash_map = dict()
for index, element in enumerate(numbers):
# 如果本次索引index值element的数,在已有hashmap中找到对应项
if target - element in hash_map:
#思考:index一定大于hash_map[target - element]
return [hash_map[target - element] + 1 ,index + 1]
hash_map[element] = index
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
# two-pointer
def twoSum1(self, numbers, target):
l, r = 0, len(numbers)-1
while l < r:
s = numbers[l] + numbers[r]
if s == target:
return [l+1, r+1]
elif s < target:
l += 1
else:
r -= 1
# dictionary
def twoSum2(self, numbers, target):
dic = {}
for i, num in enumerate(numbers):
if target-num in dic:
return [dic[target-num]+1, i+1]
dic[num] = i
# binary search
def twoSum(self, numbers, target):
for i in xrange(len(numbers)):
l, r = i+1, len(numbers)-1
tmp = target - numbers[i]
while l <= r:
mid = l + (r-l)//2
if numbers[mid] == tmp:
return [i+1, mid+1]
elif numbers[mid] < tmp:
l = mid+1
else:
r = mid-1
https://leetcode-cn.com/problems/two-sum/
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i, num in enumerate(nums):
if num in dic:
return [dic[num], i]
else:
dic[target - num] = i
# """这样写更直观,遍历列表同时查字典"""
# dct = {}
# for i, n in enumerate(nums):
# if target - n in dct:
# return [dct[target - n], i]
# dct[n] = i