您的位置:首页 > 其它

LeetCode每日一题--两数之和

2020-03-15 18:22 651 查看

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

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


  【题目】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

  • 点赞 2
  • 收藏
  • 分享
  • 文章举报
Mingw_ 发布了36 篇原创文章 · 获赞 64 · 访问量 2790 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: