码迷,mamicode.com
首页 > 其他好文 > 详细

28.leetcode167_two_sum_II

时间:2018-02-13 22:16:43      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:sort   type   inpu   操作   移动   out   read   sam   get   

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

标签:sort   type   inpu   操作   移动   out   read   sam   get   

原文地址:https://www.cnblogs.com/19991201xiao/p/8447475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!