LeetCode——Two Sum
2015-09-17 18:59
477 查看
题目
Given an array of integers, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
思路
看完题目,第一想到的是分别求出所有可能的组合,显示这种肯定不行然后想去看看有什么其他规定,比如都是正数,或者是已排序数列,然而发现都没有。
那一对一对的算肯定不行,然后想其他办法,当然最好是遍历一遍就找出来,那么我们通过正向走,向后找是遍历List,那么肯定是n(O),那么我们用一个map把前面的存起来。正向遍历,然后再去map中找互补的数。就是O(n)了。
解法
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ maps = {} result = [] for i in range(len(nums)): if maps.has_key(str(nums[i])): first = int(maps[str(nums[i])]) result.append(first) result.append(i+1) return result else: num = target-nums[i] maps[str(num)] = str(i+1) return result
相关文章推荐
- Android 自定义View——Path的使用
- 【sphinx】中文声学模型训练
- HDU 1026 Ignatius and the Princess I
- 黑马程序员 java枚举使用详解
- 黑马程序员 java反射详解
- Jni之在c++中调用java代码
- window系统svchost.exe占用CPU或者内存过高的解决方案
- Java读写MySQL数据库小实例
- ICDM Winner's Interview: 3rd place, Roberto Diaz
- iOS提示框,为什么你应该使用 MBProgressHUD?
- 面向对象编程,类切换
- maven错误解决:编码GBK的不可映射字符
- cerr与cout的区别
- 黑马程序员 Java中什么是接口回调?
- Java 内存区域和GC机制以及JVM(Java虚拟机)优化大全和案例实战
- cloudera manager配置
- APK安装出错:INSTALL_FAILED_UID_CHANGED
- 黑马程序员 java多线程总结
- ReactiveCocoa基本组件:理解和使用RACCommand
- 解决javascript加减乘除及toFixed的误差问题