LeetCode:167. Two Sum II - Input array is sorted - Python

167. 两数之和 II - 输入有序数组

问题描述:

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。

函数应该返回这两个下标值 index1index2,其中index1必须小于index2

说明:

  • 返回的下标值(index1index2不是从零开始的。
  • 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。

示例:

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

问题分析:

最近忙着毕业论文,各种糟心,好久没更新了,心里痒痒赶紧复习一下,2019年第一篇哈。

(1)题目不难,使用双指针方法。(题目已经给出了,给定的数组是有序,即从小到大)
(2)可以设置首位两个指针lowhigh,分别指向数组最左和最右,然后求和。
(3)如果两个数的和大于target,则high向左移动,否则low向右移动。
(4)如果两个数的和等于target,就直接返回即可(注意位置是1开始)

Python3实现:

# @Time   :2019/01/16
# @Author :LiuYinxing
# 双指针法


class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """

        low, high = 0, len(numbers) - 1
        while numbers[low] + numbers[high] != target:
            total = numbers[low] + numbers[high]
            if total > target:  # high 向左移动
                high -= 1
            elif total < target:  # low 向右移动
                low += 1
        return [low+1, high+1]


if __name__ == '__main__':
    solu = Solution()
    numbers, target = [2, 7, 11, 15], 9
    print(solu.twoSum(numbers, target))

声明: 总结学习,有问题或不当之处,可以批评指正哦。

题目链接

猜你喜欢

转载自blog.csdn.net/XX_123_1_RJ/article/details/86502991