leetcode第一题--two sum
Problem: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
由于水平问题,本题参考了Suool大神的思路。因为我首先想到的居然是两个for,第一个for全部,第二个for从前一个for的迭代加1开始寻找相等记录下标。
class resolution{
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int>::iterator iter, res;
vector<int> result();
res = result.begin();
for (iter = numbers.begin();iter != numbers.end();++iter)
{
for (vector<int>::iterator iter2 = iter + ;iter2!=numbers.end();++iter2)
{
if(*iter + *iter2 == target)
{
*res = iter - numbers.begin() + ;
*(++res) = iter2 - numbers.begin() + ;
return result;
}
}
}
}
};
可想而知运行超时,于是,冷静参考了Suool后,想了下这是最low的N方复杂度。既然超时,那应该是nlogn能解决的。想到排序吧就nlogn了。那就排序吧。用std::sort。
排序之后那就用头尾之和来判断,不断往里缩进直至找到答案为止。
头尾之和小于target的话,那就头要往前才能增大。
头尾之和大于target的话,那就尾要回缩才能缩小。
因为答案有且仅有一个,所以,不断缩进肯定可以找到答案。
找到到答案后,那就根据key值在原来的vector中找,大不了遍历2n就找到下标,push_back到result中就好了。
class Solution{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> result;
vector<int> temp = numbers;
std::sort(temp.begin(),temp.end());
int left = ;
int right = temp.size() - ;
int sum = ;
int index = ;
while(left < right)
{
sum = temp[left] + temp[right];
if (sum == target)
{
while(true)
{
if(numbers[index] == temp[left])
{
result.push_back(index + );
}
// must be 'else if' or the same index will be push_back when the target is composed by two same numbers
else if(numbers[index] == temp[right])
{
result.push_back(index + );
}
if(result.size() == )
{
return result;
}
index++;
}
}
else if (sum < target)
{
left++;
}
else
{
right--;
}
}
}
};
这样就行了。注意当中的else if 避免相同的值相加为target的case导致错误记录index。可以吧else if 改成 if 提交看下错误提示就知道了。
有位更叼的大神居然用n就解决了http://www.tuicool.com/articles/RBNjuu
2015/01/08:
今天有个人问我这题,然后说了以上方法,顺带写了个hash的O(n)
class Solution{
public:
vector<int> twoSum(vector<int> &numbers, int target){
vector<int> result;
unordered_map<int, int> umap;
for (int i = ; i < numbers.size(); i++){
umap[numbers[i]] = i + ;
}
for (int i = ; i < numbers.size(); i++){
int umapVal = umap[target - numbers[i]];
if (umapVal && umapVal != i + ){
result.push_back(i + );
result.push_back(umap[target - numbers[i]]);
break;
}
}
return result;
}
};
就是用hash记录每个值的下标,以便于target减去一个值之后可以O(1)时间找到剩下的知否在当前给定的值里。是的话就返回下标return了。
需要注意的是,你要找的剩下的值是否在给定的里面要加一个不是本身的判断,因为例子target = 6, 给定 3, 2, 4 的时候,umap != i + 1 就派上用场了。
2015/04/03:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> umap;
vector<int> ans;
for (int i = ; i < numbers.size(); ++i){
umap[numbers[i]] = i + ;
}
for (int i = ; i < numbers.size(); ++i){
if (umap.count(target - numbers[i]) && i + != umap[target - numbers[i]]){
ans.push_back(i + );
ans.push_back(umap[target - numbers[i]]);
}
}
return ans;
}
};
leetcode第一题--two sum的更多相关文章
- LeetCode第一题—— Two Sum(寻找两数,要求和为target)
题目描述: Given an array of integers, return indices of the two numbers such that they add up to a speci ...
- LeetCode算法题-Two Sum II - Input array is sorted
这是悦乐书的第179次更新,第181篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第38题(顺位题号是167).给定已按升序排序的整数数组,找到两个数字,使它们相加到特定 ...
- 乘风破浪:LeetCode真题_040_Combination Sum II
乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...
- 乘风破浪:LeetCode真题_039_Combination Sum
乘风破浪:LeetCode真题_039_Combination Sum 一.前言 这一道题又是集合上面的问题,可以重复使用数字,来求得几个数之和等于目标. 二.Combination Sum ...
- LeetCode算法题-Two Sum IV - Input is a BST(Java实现)
这是悦乐书的第280次更新,第296篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第148题(顺位题号是653).给定二进制搜索树和目标数,如果BST中存在两个元素,使得 ...
- LeetCode算法题-Path Sum III(Java实现)
这是悦乐书的第227次更新 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第94题(顺位题号是437).您将获得一个二叉树,其中每个节点都包含一个整数值.找到与给定值相加的路径数 ...
- LeetCode算法题-Range Sum Query Immutable(Java实现)
这是悦乐书的第204次更新,第214篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第70题(顺位题号是303).给定整数数组nums,找到索引i和j(i≤j)之间的元素之 ...
- LeetCode算法题-Path Sum(Java实现)
这是悦乐书的第169次更新,第171篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第28题(顺位题号是112).给定二叉树和整数sum,确定树是否具有根到叶路径,使得沿路 ...
- leetcode第一题(easy)
第一题:题目内容 Given an array of integers, return indices of the two numbers such that they add up to a sp ...
随机推荐
- PAAS平台7×24小时可用性应用设计
如今非常多企业都在搭建自己的私有PAAS平台,当然也有非常多大型互联网公司搭建共同拥有PAAS平台(比如SAE/BAE/JAE(jae.jd.com)).那么使用PAAS平台来部署SAAS应用有哪些优 ...
- ASP.NET程序读取二代身份证(附源码)
原文:ASP.NET程序读取二代身份证(附源码) 一般来说winform应用程序解决这个问题起来时很容易的,web应用程序就麻烦一点了. 这里我说说我的解决思路: 一.你必要有联机型居民身份证阅读器一 ...
- mahout源码KMeansDriver分析之五CIMapper初探
接着上篇,继续分析代码.下面就到了MR的循环了,这里MR应该算是比较好理解的,重点是退出循环的条件设置,即如何判断前后两次中心点误差小于给定阈值. 首先,while循环: while (iterati ...
- POJ 3982 序列 塔尔苏斯问题解决
而且还加入了大量的主题,直接或模板Java我们能够在水. 除了循环33它的时间,计算A99它是第几,输出准确回答. #include <stdio.h> #include <stri ...
- oracle connect by 说明
Oracle能够通过START WITH . . . CONNECT BY . . .子句来实现SQL分层查询,这递归查询 例如: select level||'月' 月份 from dual con ...
- HDU 4123 Bob’s Race 树的直径+单调队列
题意: 给定n个点的带边权树Q个询问. 以下n-1行给出树 以下Q行每行一个数字表示询问. 首先求出dp[N] :dp[i]表示i点距离树上最远点的距离 询问u, 表示求出 dp 数组中最长的连续序列 ...
- org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: sys.entity.Role; nested exception is org.hibernate.PersistentObjectException: 的解决方案
1.错误信息 org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist ...
- Codeforces 135A-Replacement(思维)
A. Replacement time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...
- aul 学习测试(测量)
-------------------aul5 ----------test0------------------------- select file#,rfile#,name from v$dat ...
- Oracle安装及使用入门
新手Oracle安装及使用入门 一.安装Oracle Step1 下载oracle压缩包并解压到同一文件夹下面 Step2 双击setup.exe进行安装 Step3:进入如下界面配置: 邮箱可不 ...