Q167 Two Sum II - Input array is sorted

时间:2022-05-11
本文章向大家介绍Q167 Two Sum II - Input array is sorted,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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
解题思路:

参考题目: Q1 Two Sum

这道题与 Q1 Two Sum 不同的是给定的列表是排好序的。如果按照 Q1 Two Sum 的思路,时间复杂度和空间复杂度均为 O(n)。

既然是排序好的列表,那么就应该利用这样一个优势。

方法一:时间复杂度为 O(nlgn),空间复杂度为 O(1) 。具体做法就是依次遍历列表中的元素,得到目标值与元素的差值,然后在剩余的元素中采用二分查找。

方法二:时间复杂度为 O(n),空间复杂度为 O(1) 。利用两个指针,一个指向列表头,一个指向列表尾。将头尾两元素值相加与目标值相比,如果比目标值小,则头指针向前移动;否则,尾指针向后移动。不断缩小范围,直到找到相加值与目标值相等的两个元素,否则返回None。

程序实现最终采用了方法二。

注意点:

返回的索引不是从0开始的,而是从1开始的。

Python实现:
class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        lens = len(numbers)
        if lens == 0:
            return None
        l, h = 0, lens - 1   # 头尾两个指针
        while l < h:     
            tar = numbers[l] + numbers[h]
            if tar == target:
                return [l+1, h+1]
            elif tar < target:
                l += 1
            else:
                h -= 1  
        return None

a = [2,3,5,7]
b = 10
c = Solution()
print(c.twoSum(a,b))   # [2,4]
总结:

方法二为两指针法,是一种常用的方法。它适用于排好序的列表