友情提示:点击上面的“+”展开目录以便查看具体的题目
Two Sum - Input array is sorted
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.
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. Please note that your returned answers (both index1 and index2) are not zero-based.
注意事项
You may assume that each input would have exactly one solution.
样例
Given nums = [2, 7, 11, 15]
, target = 9
return [1, 2]
这道题特别简单,唯一要注意的一点就是有相同数字时的处理,如[1,1,3,4] target=2,方法见下面代码。
class Solution:
"""
@param nums {int[]} n array of Integer
@param target {int} = nums[index1] + nums[index2]
@return {int[]} [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum(self, nums, target):
# Write your code here
for i in range(len(nums)):
if target-nums[i] in nums:
if (target-nums[i])!=nums[i]:
return [i+1,nums.index(target-nums[i])+1]
else:
if nums.count(nums[i])>1:
return [i+1,nums.index(target-nums[i])+2]