LeetCode刷题笔记——1. 两数之和
2019-10-08 09:41
169 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_37046391/article/details/102365951
LeetCode刷题笔记——1. 两数之和
题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
利用两个循环解决
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): for j in range(i+1 , len(nums)): if nums[i] + nums[j] == target: return [i, j]
结果:
改进方法
利用python的字典来解决问题
首先,遍历列表,将列表中的第一个添加到字典当中。
在之后的列表中,每遍历一个节点,就在字典中寻找是否存在与其相加的和等于目标值的数,若存在则返回这两个数在列表中的位置,否则将该节点加入列表中并继续遍历下一个节点。
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashmap = {} for index, num in enumerate(nums): another_num = target - num if another_num in hashmap: return [hashmap[another_num], index] hashmap[num] = index return None
很明显,时间复杂度降低了。
相关文章推荐
- 哈希表学习笔记及LeetCode编程练习之两数之和and快乐数
- Leetcode刷题笔记 两数之和
- LeetCode 题库1. 两数之和 答案及笔记
- leetcode刷题笔记-两数相加(1)
- LeetCode刷题笔记之1:两数之和Python
- LeetCode刷题笔记 442. 数组中重复的数据
- LeetCode初级算法笔记整理
- LeetCode刷题笔记 39. 组合总和
- LeetCode笔记:389. Find the Difference
- LeetCode刷题笔记三
- [leetCode刷题笔记]2017.02.05
- LeetCode刷题笔记——LeetCode使用介绍
- 【leetcode】1. 两数之和——寻找两数和为目标值得组合
- leetcode笔记:Anagrams
- Leetcode刷题笔记之 Add Two Numbers(python实现)
- LeetCode刷题笔记 406. 根据身高重建队列
- LeetCode 423. Reconstruct Original Digits from English解题笔记
- LeetCode刷题笔记(Two Sum)
- Leetcode解题笔记-Rotate Array
- LeetCode笔记:482. License Key Formatting