leetcode上问题描述:
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].
解题的思路对是数组做排序,然后设置两个指针,分别从最大值和最小值两头开始,判断两个指针对应的数值相加与目标值的区别,来调整两个指针移动的位置。最终会选取到所需的那两个数。空间复杂度O(n),时间复杂度O(nlogn + n)。
在实现上述思路过程中,要注意题目的关键点:
1. 返回的是那两个数在原数组中的index,而非这两个数的具体值
2. 同一个元素不能使用两次
这两个关键点也正是题目的两个坑。针对关键点一:千万不要返回排序后的index,要用个dict记录原始数组中各值的index;针对关键点二:切记原数组中是允许多个数值相同的情况。一开始我使用dict记录计数时,key=原数组中的数值,value=该数值的index。因此当数组中存在相同的两个数时,dict里始终只记录了一个index,测试case就会跑挂掉。要倒过来记录。
好了,上代码,
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#dict
nums_dict=[(idx, nums[idx]) for idx in range(len(nums))]
#nums_dict = {}
#for idx in range(len(nums)):
# nums_dict[idx]=nums[idx]
#sort nums by value
nums_dict = sorted(nums_dict.items(), key=lambda item:item[1])
#two idxs
min_idx=0
max_idx=len(nums)-1
find = False
while (min_idx < max_idx):
curr_sum = nums_dict[min_idx][1] + nums_dict[max_idx][1]
if curr_sum == target:
find = True
break
elif curr_sum > target:
max_idx -= 1
elif curr_sum < target:
min_idx += 1
if find:
return [nums_dict[min_idx][0], nums_dict[max_idx][0]]
else:
return []