刷题总结leetcode 1.twosum
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
python解法:
将问题转化为寻找 target-x, 使用hashmap的可以加快索引速度,但是要注意的是如果直接先建立完整的map就会出现索引冲突的问题,所以为了避免这个问题,可以在遍历过程中一边遍历一边添加map就不会出现索引冲突了
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap = {}
for i, x in enumerate(nums):
y = target - x
if y in hashmap:
return hashmap[y],i
hashmap[x]=i
拓展
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
因为有序就可以使用两个指针已在头一个在尾,将收尾相加求和与target比较,因为有序如果大于target就把i 右移 如果小于就把j 左移
def twoSum1(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
l = len(numbers)
i, j = 0, l-1
while i < j:
if numbers[i] + numbers[j] == target:
return i+1, j+1
elif numbers[i] + numbers[j] > target:
j -= 1
else:
i += 1