創(chuàng)建于:20170308
原文鏈接:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/?tab=Description
1 題目
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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
2 python代碼
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
i=0
j=len(numbers)-1
while(i < j):
tag2=target - numbers[j]
#這里一開始對j進行了判斷,認為target > numbers[j],這是不對的,如果有負數(shù)呢?
if numbers[i] < tag2:
i+=1
continue
elif numbers[i] == tag2:
return [i+1,j+1]
else:
j-=1
#i+=1 這里不要對i進行++
3 算法解析
雙指針問題,頭指針i,尾指針j。
先固定j,然后移動i,當i移動結(jié)束,再移動j。
需要考慮0和負數(shù)的情況。