28.leetcode167_two_sum_II

Posted vlice

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]    

 


以上是关于28.leetcode167_two_sum_II的主要内容,如果未能解决你的问题,请参考以下文章

MT167反复放缩

AtCoder Beginner Contest 167(补题)

在centos 7下安装mysql 5.7.17

PHP å...一个??|å??Šè§'æ-‡A-A ??§A??,A,<A ... <ダ??ã,§

PHP å...¨è§'ã,'å??Šè§'ã??«ã?™一种,&

LeetCode第5天 - 283. 移动零 | 167. 两数之和 II - 输入有序数组