LeeCode每日一题--两数之和

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

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


  【题目】1.两数之和

  题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
  示例:

        给定 nums = [2, 7, 11, 15], target = 9
        因为 nums[0] + nums[1] = 2 + 7 = 9
		所以返回 [0, 1]

  思路一:通过两层for循环,因为不能使用数组中同样的元素,第一层从头遍历到尾部元素减一,第二层遍历从第一层的 i 值遍历到尾。代码如下:

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

  运行结果:

  思路二:通过字典作为存储工具,利用哈希表的方式进行求解。代码如下:

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

  运行结果:
在这里插入图片描述
  关于其中一些知识的链接:

  Python enumerate函数

  Python 字典

  算法动画详解,推荐观看《动画图解算法:两数之和》

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

  注明:
  题目来源:力扣(LeetCode)
  链接:https://leetcode-cn.com/problems/two-sum

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

猜你喜欢

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