Leetcode 1 Two Sum
2015-06-11 15:37
399 查看
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
使用Hash存储每个值所对应的数组下标。
h = { :a[index1] => index1, :a[index2] => index2, ... }
需要两个值加起来等于Sum,只需要检查是否在Hash中存在Sum减去第一个值后第二个值的key(第一个值通过遍历数组得到),并且这两个值不是同一个数(对应相等的数组下标)。
需要注意最后求的两数是在数列中的顺序,应为数组下标+1。
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
使用Hash存储每个值所对应的数组下标。
h = { :a[index1] => index1, :a[index2] => index2, ... }
需要两个值加起来等于Sum,只需要检查是否在Hash中存在Sum减去第一个值后第二个值的key(第一个值通过遍历数组得到),并且这两个值不是同一个数(对应相等的数组下标)。
需要注意最后求的两数是在数列中的顺序,应为数组下标+1。
def two_sum(num, target) h = {} num.length.times {|i| h[num[i]] = i} num.length.times {|i| return i+1, h[target-num[i]]+1 if h[target-num[i]] and h[target-num[i]] > i} end
相关文章推荐
- MFC ActiveX GUID
- 关于mysql error code 1005 errno135的问题
- 单例模式
- Mybatis 数据库表增删改查
- struts 2吊牌s:if 、s:iterator注意
- HTML、CSS部分
- 唯购:开通微信商城,费用全免!
- 函数参数中指向指针的指针
- com.mongodb.MongoException$CursorNotFound: cursor not found on server异常处理
- liunx重启机器命令
- MessageBox、::MessageBox 、AfxMessageBox三者的区别
- 工作记录一
- 调用window.showModalDialog(),不能调用window.location.reload()和提交表单时打开新窗口的解决方案
- php读取excel文档内容(转载)
- CentOS6.5配置PHP CI程序
- android 实践基础 AndroidUI性能优化-2015/06/11
- JAVA集群分布式和网络设计的浅析(转载!)
- 如何分析GRE句子填空结构?
- 谈OSSIM服务器内存开销问题
- 准确率的计算