【LeetCode】167. Two Sum II - Input array is sorted

我的个人微信公众号:Microstrong

微信公众号ID:MicrostrongAI

微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!

知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities

Github:https://github.com/Microstrong0305

个人博客:https://blog.csdn.net/program_developer

167. 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.

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.

解题思路

(1)双指针解法,时间复杂度为O( n) 

已经AC的代码:

from typing import List


class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        if len(numbers) <= 0:
            return None
        low = 0
        high = len(numbers) - 1
        while low < high:
            if numbers[low] + numbers[high] == target:
                return [low + 1, high + 1]
            elif numbers[low] + numbers[high] > target:
                high -= 1
            else:
                low += 1


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

(2)暴力解法(双重循环),时间复杂度为O(n^2)

通过两次循环,每次循环遍历列表,这种算法的时间复杂度是O(n^2)

代码提交后:Time Limit Exceeded,代码如下:

    # 方法二:暴力解法(双重循环)
    def twoSum2(self, numbers: List[int], target: int) -> List[int]:
        if len(numbers) <= 0:
            return None

        for i in range(len(numbers)):
            for j in range(i + 1, len(numbers)):
                if numbers[i] + numbers[j] == target:
                    return [i + 1, j + 1]

(3)二分搜索法,时间复杂度为O(n log n)

数组是有序的,那么我们很容易想到使用二分搜索法是不是可以用于这个问题呢?我们可以每次判断target-num[i]对应的值是否在num[i+1:]中,这个时候算法的复杂度变成了O(nlogn)

已经AC的代码如下:

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        length = len(numbers)
        for i in range(length):
            difference = target - numbers[i]
            index = self.search_Bin(numbers, difference, i + 1)
            if index != -1:
                return [i + 1, index + 1]

    def search_Bin(self, numbers, target, start):
        if len(numbers) <= 0:
            return -1
        low = start
        high = len(numbers) - 1
        while low <= high:
            middle = (low + high) // 2
            if numbers[middle] == target:
                return middle
            elif numbers[middle] > target:
                high = middle - 1
            else:
                low = middle + 1
        return -1

Reference

【1】Leetcode 167:两数之和 II - 输入有序数组(最详细解决方案!!!),地址:https://blog.csdn.net/qq_17550379/article/details/80512745   

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页