1. Two Sum [easy] (Python)
来源:互联网 发布:网络交换机品牌排行 编辑:程序博客网 时间:2024/05/18 01:05
题目链接
https://leetcode.com/problems/two-sum/
题目原文
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题目翻译
给定一个整数数组nums,返回数组中“和是某个给定值target”的两个数的下标。假设对于每次输入有且只有一个解。
比如:给定nums = [2, 7, 11, 15],target = 9,因为nums[0] + nums[1] = 2 + 7 = 9,所以返回[0, 1]。
思路方法
思路一
直观思路,暴力求解,两重循环。效率很低。。。
代码
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in xrange(len(nums) - 1): for j in xrange(i+1, len(nums)): if nums[i] + nums[j] == target: return [i, j]
思路二
由于题目说了有且只有唯一解,可以考虑两遍扫描求解:第一遍扫描原数组,将所有的数重新存放到一个dict中,该dict以原数组中的值为键,原数组中的下标为值;第二遍扫描原数组,对于每个数nums[i]查看target-nums[i]是否在dict中,若在则可得到结果。
当然,上面两遍扫描是不必要的,一遍即可,详见代码。
代码
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ keys = {} for i in xrange(len(nums)): if target - nums[i] in keys: return [keys[target - nums[i]], i] if nums[i] not in keys: keys[nums[i]] = i
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52039233
- 1. Two Sum [easy] (Python)
- 【Easy】1. Two Sum
- 1. Two Sum easy
- 1. Two Sum (Easy)
- 1.[easy] Two Sum
- 1.Two Sum 难度:easy
- leetcode 1. Two Sum [Easy]
- LeetCode 1. Two Sum (Easy)
- 371. Sum of Two Integers [easy] (Python)
- Leetcode 1. Two Sum (Easy) (cpp)
- Leetcode 1. Two Sum (Easy) (java)
- 2017.2.25 1. Two Sum [easy]
- Leetcode[Easy] - Two Sum
- 【Leetcode】Two sum(easy)
- Two Sum(easy)
- Two Sum(easy)
- leetcode Two Sum easy
- #1 Two Sum(Easy)
- const
- SDUToj 1028 Catch That Cow (BFS)
- 仿SegmentFault系列(一) PopupMenu
- linux 命令 ln(软件升级很好用)
- jQuery EasyUI DataGrid - 格式化列(formatter )
- 1. Two Sum [easy] (Python)
- iOS键盘与文本框的处理(二)
- Attention and Memory in Deep Learning and NLP(深度学习和NLP中的注意和记忆机制) 阅读笔记
- hdu5754 Life Winner Bo (博弈混合)
- 基于arm的音乐播放器制作
- HDU5754 2016年第三场多校C
- HDU 1203 背包问题
- 【Python】基础学习——列表(list),元祖(tuple),字典(dict),字符串(string),集合(set)
- 【BLE】CC2541之SBL修改bootloader大小