leetcode 167[easy]---Two Sum II

来源:互联网 发布:如何骂淘宝天下小二 编辑:程序博客网 时间:2024/05/02 00:17

难度:easy

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

思路:题意简单,找到给定list的两个数,这两个数的和等于target,并以list的形式返回index。发现在leetcode中用index()好像不行。

          双支针的方法,从头尾向中间走,直到两指针的和为target。