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的更多相关文章

  1. LeetCode第一题—— Two Sum(寻找两数,要求和为target)

    题目描述: Given an array of integers, return indices of the two numbers such that they add up to a speci ...

  2. LeetCode算法题-Two Sum II - Input array is sorted

    这是悦乐书的第179次更新,第181篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第38题(顺位题号是167).给定已按升序排序的整数数组,找到两个数字,使它们相加到特定 ...

  3. 乘风破浪:LeetCode真题_040_Combination Sum II

    乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...

  4. 乘风破浪:LeetCode真题_039_Combination Sum

    乘风破浪:LeetCode真题_039_Combination Sum 一.前言     这一道题又是集合上面的问题,可以重复使用数字,来求得几个数之和等于目标. 二.Combination Sum ...

  5. LeetCode算法题-Two Sum IV - Input is a BST(Java实现)

    这是悦乐书的第280次更新,第296篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第148题(顺位题号是653).给定二进制搜索树和目标数,如果BST中存在两个元素,使得 ...

  6. LeetCode算法题-Path Sum III(Java实现)

    这是悦乐书的第227次更新 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第94题(顺位题号是437).您将获得一个二叉树,其中每个节点都包含一个整数值.找到与给定值相加的路径数 ...

  7. LeetCode算法题-Range Sum Query Immutable(Java实现)

    这是悦乐书的第204次更新,第214篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第70题(顺位题号是303).给定整数数组nums,找到索引i和j(i≤j)之间的元素之 ...

  8. LeetCode算法题-Path Sum(Java实现)

    这是悦乐书的第169次更新,第171篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第28题(顺位题号是112).给定二叉树和整数sum,确定树是否具有根到叶路径,使得沿路 ...

  9. leetcode第一题(easy)

    第一题:题目内容 Given an array of integers, return indices of the two numbers such that they add up to a sp ...

随机推荐

  1. java 生产者消费者问题 并发问题的解决(转)

    引言 生产者和消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一个存储空间,如下图所示,生产者向空间里存放数据,而消费者取用数据,如果不加以协调可能会出现以下情况: 生产者消费者图 ...

  2. Spring先进的交易管理困难剖析

    1Spring事务传播行为 所谓事务传播行为就是多个事务方法相互调用时,事务怎样在这些方法间传播.Spring支持7种事务传播行为 PROPAGATION_REQUIRED(增加已有事务) 假设当前没 ...

  3. 于Unity3D调用安卓AlertDialog

    例如,下面的示例代码演示 package com.sample.sampletest; import android.app.AlertDialog; import android.content.D ...

  4. 写作Openwrt固件

    启动tftp软体.并设置文件夹的固件文件(Current Dircctory)和serverIP(Service interface).server指PC机.图.:                   ...

  5. linux的自动化操作相关使用方法汇总(转)

    linux系统的web网站在运营状态时,我们常需要对网站进行维护,例如查看资源剩余并做出响应.日志分割.数据整理,在特定状态执行特定任务等等,这些都会需要linux能实现自动执行某些任任务.本篇博文介 ...

  6. 实现一个与内容合二为一的ActionBar动画效果

    实现一个与内容合二为一的ActionBar动画效果,让你的actionbar更生动.以下是效果图: 这样的效果的优点是让actionbar也成为了内容的一部分,实际应用的效果比图片展示的效果要好,除了 ...

  7. SVN在branch兼并和游戏patch(1)

    近期要hadoop2.4关于上面的行hdfs raid,但在此之前hdfs raid如svn 的branch发展,领导人希望patch方式hdfs raid功能进球trunk里面去,这里涉及到svn ...

  8. ServiceStack.Redis——Redis于.net向上client解

    ServiceStack.Redis--Redis于.net向上client解 源代码和使用: https://github.com/ServiceStack/ServiceStack.Redis 样 ...

  9. SQL2000 MD5加密

    原文:SQL2000 MD5加密 /***************************************************************************** * Na ...

  10. Nyoj 天下第一(spfa)

    描述 AC_Grazy一直对江湖羡慕不已,向往着大碗吃肉大碗喝酒的豪情,但是“人在江湖漂,怎能 不挨刀",”人在江湖身不由己",如果自己的武功太差,在江湖会死的很惨,但是AC_Gr ...