第1.3节 两数求和II - 数组已排序

2017-03-08  本文已影响0人  比特阳

创建于: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],这是不对的,如果有负数呢?
            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移动结束,再移动j。
需要考虑0和负数的情况。

上一篇下一篇

猜你喜欢

热点阅读