zoukankan      html  css  js  c++  java
  • [LeetCode] 167. 两数之和 II

    题目链接 : https://leetcode-cn.com/problems/two-sum-i-input-array-is-sorted/

    题目描述:

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

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

    说明:

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

    示例:

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

    思路:

    思路一:和 1. 两数之和 | 题解链接一样!使用 字典解决! 时间复杂度也是 (O(n))

    思路二: 双指针

    因为是有序数组, 我们用一头一尾两个指针移动调整使它之和接近 target

    时间复杂度: (O(n))

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

    思路三: 二分搜索

    就是说固定一个数num, 用二分搜索找target - num

    时间复杂度: (O(nlogn))

    class Solution:
        def twoSum(self, numbers: List[int], target: int) -> List[int]:
            n = len(numbers)
            for i in range(n - 1):
                num = target - numbers[i]
                idx = bisect.bisect_left(numbers, num, i + 1, n)
                if idx < n and numbers[idx] == num:
                    return [i + 1, idx + 1]
    
  • 相关阅读:
    Christmas Jump(k_push)
    cloudyarn(k_push)
    Eye sketch
    Candy Treasure Box
    Active Ball
    Lotus words
    Super Fish
    [POJ2436] Disease Management
    [bzoj3376] Cube Stacking 方块游戏
    [POJ3009] Curling 2.0
  • 原文地址:https://www.cnblogs.com/powercai/p/11312442.html
Copyright © 2011-2022 走看看