LeeCode每日一题--两数之和II-输入有序数组

  【前言】坚持日更LeeCode刷题系列

    不积跬步,无以至千里;不积小流,无以成江海。愿与诸君共勉!


  【题目】136.只出现一次的数字

    题目描述:给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。函
数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。

    说明:

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


    示例:

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

    思路一:首先,我们还是来用暴力求解的方法来思考此题。具体步骤如下:
         1.建立两个循环来遍历数组
         2.如果两个index不相等(排除相同的数相加)并且对应index下的数相加为target,则返回列表。
         具体代码如下:

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        result_list = []
        for i in range(len(numbers)):
            for j in range(len(numbers)):
                if(i!=j and numbers[i]+numbers[j]==target):
                    result_list.append(i+1)
                    result_list.append(j+1)
                    return result_list

    运行结果:出现了超时错误,采用两层循环的方式,时间复杂度为O(n^2),因此对于过长的列表时,会出现超时的现象。


    思路二:可参考我这篇中利用字典存储,模拟哈希表解决此题。具体代码如下:

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {}      #因为我们想得到index,所以我们将num作为键
        for index,num in enumerate(numbers):
            another_num = target - num
            if(another_num in hashmap):
                return [hashmap[another_num]+1,index+1] #注意return时两个index的顺序
            else:
                hashmap[num] = index
        return None

    运行结果:
    在这里插入图片描述

    思路三:很显然官方是不会出两个一样的题的,那么题目中还有一个重点标记的条件升序排列,那么我们应该如何去利用这个条件呢?我首先想到的是二分查找的方式,并且在题解中看到了一个前辈的关于二分详细的思考,于是直接引出大佬链接就好了,有兴趣的朋友可以去了解下。


    关于其中一些知识的链接:
    二分姿势

    分享就到这里了,欢迎大家一起交流讨论。


    注明

    题目来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted

发布了32 篇原创文章 · 获赞 62 · 访问量 1294

猜你喜欢

转载自blog.csdn.net/Mingw_/article/details/104800851