LeetCode OJ:Two Sum(两数之和)
2015-10-05 17:56
519 查看
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
给一个vector,一个value,要求求出vector之内的两数相加之和等于value的两个index。
这里的基本思想是用一个map先来保存vector元素的值与他们对应的index,然后循环vector,用value减去每个数之后,把差值直接放到map里面去寻找
看能不能找到对应的index,大体上就是这个思想,下面详见代码:
附上java版本的代码,方法比上面简洁一点。不过道理还是基本一样的:
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
给一个vector,一个value,要求求出vector之内的两数相加之和等于value的两个index。
这里的基本思想是用一个map先来保存vector元素的值与他们对应的index,然后循环vector,用value减去每个数之后,把差值直接放到map里面去寻找
看能不能找到对应的index,大体上就是这个思想,下面详见代码:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> index; vector<int> result; int sz = nums.size(); for (int i = 0; i < sz; ++i){ index[nums[i]] = i; } map<int, int>::iterator it; for (int i = 0; i < sz; ++i){ if ((it = index.find(target - nums[i])) != index.end()){ if (it->second == i) continue;//这一步要注意,防止找到的index与当前的i是相等的 result.push_back(i + 1); result.push_back(it->second + 1); break; } } return result; } };
附上java版本的代码,方法比上面简洁一点。不过道理还是基本一样的:
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); int [] result = new int[2]; for(int i = 0; i < nums.length; ++i){ if(m.containsKey(nums[i])){ int index = m.get(nums[i]); result[0] = index + 1; result[1] = i + 1; break; }else{ m.put(target-nums[i] ,i);//很关键! } } return result; } }
相关文章推荐
- revit二次开发--获取element的三种方法
- Gson解析(2)——Gson注解和GsonBuilder
- QT5 学习之路21---文件对话框
- poj 1466 Girls and Boys (最大独立集)
- 《栈的应用 版本1.0》
- Have Lunch Together
- HBase连接池 -- HTablePool被Deprecated以及可能原因是什么
- 解析Json数据并缓存图片到sdcard
- 剑指Offer第八章面试题(Java版)
- Step-By-Step Installation of RAC with RAW Datafiles on Windows 2000
- editplus查找替换的正则表达式应用
- Cocos2d-x 开发环境搭建
- HBase建表函数createTable的几点说明
- Python - 刷博客浏览数
- CodeForcesGym 100753A A Journey to Greece
- 搭建hibernate时 'hibernate.dialect' must be set when no Connection available错误
- iOS开发网络篇—数据缓存
- Sublime Text的那些事
- HBase查询一条数据的过程.
- HADOOP中的CRC数据校验文件