28.leetcode167_two_sum_II

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.题目分析

双指针操作,分别从头和尾开始遍历,相加和比目标数字小,前指针移动一位;反之,后指针移动一位

3.解题思路

 1 class Solution(object):
 2     def twoSum(self, numbers, target):
 3         """
 4         :type numbers: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         i=0
 9         j=len(numbers)-1
10         while i<j: #前指针永远在后指针前面
11             if target-numbers[j]>numbers[i]: 
12                 i+=1 #前指针移动
13                 continue
14             if target-numbers[j]<numbers[i]:
15                 j-=1 #后指针移动
16                 continue
17             else:
18                 return [i+1,j+1]    
原文地址:https://www.cnblogs.com/19991201xiao/p/8447475.html