leetcode167. Sum of Two Numbers II-Input Ordered Array-Double Pointer

167. Sum of Two Numbers II-Input an ordered array

Difficulty: simple

Given an ordered array that has been arranged in ascending order , find two numbers so that their sum is equal to the target number.

The function should return the two subscript values ​​index1 and index2, where index1 must be less than index2.

Description:

  • The returned subscript values ​​(index1 and index2) are not zero-based.
  • You can assume that each input only corresponds to a unique answer, and you cannot reuse the same elements.

Example:

输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 27 之和等于目标数 9 。因此 index1 = 1, index2 = 2

Solution

The list is sorted in ascending order, so use double pointers to click on both sides. If the sum is small, the left pointer will move to the right, and if the sum is large, the right pointer will move to the left ((

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        l=0;r=len(numbers)-1
        while l<r:
            if numbers[l]+numbers[r]==target:
                return ([l+1,r+1])
            elif numbers[l]+numbers[r]>target:
                r-=1
            else:
                l+=1

Guess you like

Origin blog.csdn.net/qq_45268474/article/details/108455654