LeetCode刷题笔记之1:两数之和Python
2019-04-26 19:15
417 查看
原题目
给定一个整数数组
nums和一个目标值
target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
[code]给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
Solution:
暴力破解:(时间复杂度为O(N^2))
[code]class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): for j in range(len(nums)): if i!=j: if nums[i] + nums[j] == target: return(i,j)
solution2:用字典dict模拟HashMap,时间复杂度为O(N)
[code]class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict = {} for i,m in enumerate(nums): if target - m is not None: return [i,dict.get(target - m)] dict.get(m) = i
相关文章推荐
- python leetcode刷题记录(1)-两数之和
- [leetcode, python] Two Sum 两数之和等于某数
- Leetcode——两数之和(twoSum)、三数之和(threeSum)——Python
- leetcode解题笔记-word-ladder (python版)
- leetcode的python实现 刷题笔记7: 反转整数
- [leetcode, python] Two Sum 两数之和等于某数
- leetcode的python实现 刷题笔记27:移除元素
- leetcode的python实现 刷题笔记74:搜索二维矩阵(二分查找的思想)
- leetcode--两数之和--python
- LeetCode刷题笔记1041:困于环中的机器人(Python实现)
- LeetCode刷题笔记53:最大子序和(Python实现)
- LeetCode刷题笔记792:匹配子序列的单词数(Python实现)
- 【数据结构】Hash表简介及leetcode两数之和python实现
- [leetcode, python] Two Sum 两数之和等于某数
- LeetCode 2 两数相加 Python
- LeetCode刷题笔记985:查询后的偶数和(Python实现)
- LeetCode刷题笔记342:4的幂(Python实现)
- (python)leetcode刷题笔记 02 Add Two Numbers
- LeetCode题解(python)-29. 两数相除
- leetcode的python实现 刷题笔记9:回文数 暴力解法和进阶算法