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
运行结果:
关于其中一些知识的链接:
分享就到这里了,欢迎大家一起分享交流。
注明:
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
- 点赞 2
- 收藏
- 分享
- 文章举报
相关文章推荐
- LeetCode每日一题 008 两数之和
- LeetCode每日一题 009 两数相加
- Leetcode每日一道 -- 两数之和
- LeetCode每日一题--两数之和II-输入有序数组
- 每日一题 001 —— LeetCode 001 两数之和
- LeetCode每日一题——T1. 两数之和(易):三种解法:暴力循环、两遍哈希表、一遍哈希表
- LeetCode每日一题——T2. 两数相加(中):链表
- (LeetCode每日一刷01)两数之和
- Leetcode每日一道 -- 两数相加
- leetcode每日一题,两数之和
- leetCode解题记录1 - 两数之和(JS,TS,PY版)
- 【leetcode每日一题】NO86.Partition List
- leetcode:198 House Robber-每日编程第二十二题
- leetcode1---两数之和
- LeetCode刷题笔记——1. 两数之和
- LeetCode每日一题--最后一个单词的长度
- 两数之和错误示范版(leetcode)
- leetcode:172 Factorial Trailing Zeroes-每日编程第二十四题
- LeetCode:两数之和
- leetcode 每日一题 101. Symmetric Tree