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

LeetCode TwoSum II 题解
本文针对LeetCode上的TwoSum II问题提供了一种高效解决方案,利用数组已排序的特点,采用从两端向中间逼近的方法,将时间复杂度降低到O(N),并附有Python代码实现。

题目地址:Two Sum II - Input array is sorted - LeetCode


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.

Note:

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.
Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

这道题目最容易想到的是穷举法,但肯定会超时,而且没有利用有序这个特性。
然后就可以想到穷举的时候进行二分查找,这样就利用了有序这个特性。

Python解法如下:

class Solution:
    def twoSum(self, numbers: list, target: int) -> list:
        result = [0, 0]
        length = len(numbers)
        flag = 0

        def search(begin, end, number):
            nonlocal numbers, result, flag
            if begin > end:
                return
            middle = (begin+end)//2
            if numbers[middle] == number:
                flag = 1
                result[1] = middle+1
                return
            elif numbers[middle] < number:
                search(middle+1, end, number)
            else:
                search(begin, middle-1, number)
        for i in range(0, length-1):
            search(i+1, length-1, target-numbers[i])
            if flag == 1:
                result[0] = i+1
                return result

然后把递归的二分查找改为迭代的二分查找:

class Solution:
    def twoSum(self, numbers: list, target: int) -> list:
        result = [0, 0]
        length = len(numbers)
        flag = 0

        def search(begin, end, number):
            nonlocal numbers, result, flag
            while begin <= end:
                middle = (begin+end)//2
                if numbers[middle] == number:
                    flag = 1
                    result[1] = middle+1
                    return
                elif numbers[middle] < number:
                    begin = middle+1
                else:
                    end = middle-1
        for i in range(0, length-1):
            search(i+1, length-1, target-numbers[i])
            if flag == 1:
                result[0] = i+1
                return result

可以通过所有样例了,但结果不让人满意,随后可以想到既然是有序的,可以从两边向中间逼近:

class Solution:
    def twoSum(self, numbers: list, target: int) -> list:
        result = [0, 0]
        length = len(numbers)
        begin = 0
        end = length-1
        while begin < end:
            temp = numbers[begin]+numbers[end]
            if temp == target:
                result[0] = begin+1
                result[1] = end+1
                return result
            elif temp > target:
                end -= 1
            else:
                begin += 1

这样时间复杂度就变为了O(N)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值