LeetCode Two Sum
2015-12-11 21:42
453 查看
LeetCode解题之Two Sum
原题
给一个int型数组,要求找出其中两个和为特定值的数的坐标。注意点:
返回的坐标一要比坐标二小
最小的坐标是1,不是0
例子:
输入: numbers={2, 7, 11, 15}, target=9
输出: index1=1, index2=2
解题思路
第一遍遍历整个数组,用map记录数值和它的坐标,第二遍遍历数组,判断(目标数字-当前数字)是否在map中,如果在,且它的下标与当前数字的下标不相同,则说明存在这两个数,返回坐标。AC源码
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ hash_map = {} for index, value in enumerate(nums): hash_map[value] = index for index1, value in enumerate(nums): if target - value in hash_map: index2 = hash_map[target - value] if index1 != index2: return [index1 + 1, index2 + 1]
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法