第1.3節(jié) 兩數(shù)求和II - 數(shù)組已排序

創(chuàng)建于: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],這是不對的,如果有負數(shù)呢?
            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移動結(jié)束,再移動j。
需要考慮0和負數(shù)的情況。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容