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. 网络语音视频技术浅议 Visual Studio 2010(转)

    我们在开发实践中常常会涉及到网络语音视频技术.诸如即时通讯.视频会议.远程医疗.远程教育.网络监控等等,这些网络多媒体应用系统都离不开网络语音视频技术.本人才疏学浅,对于网络语音视频技术也仅仅是略知皮 ...

  2. 82. NotesclientPrint相同的信息,以状态栏的问题

    这可能是一个小问题.但其他人也应该得到满足.在Notesclient使用LotusScript的Print当该语句是输出到状态栏,假设实际参数传递多次调用相同,状态栏将显示只有一次的信息. 例如: P ...

  3. BZOJ 2878([Noi2012]-失落的游乐园树DP+出站年轮加+后市展望DP+vector的erase)

    2878: [Noi2012]迷失乐园 Time Limit: 10 Sec  Memory Limit: 512 MBSec  Special Judge Submit: 319  Solved:  ...

  4. 中国澳门sinox很多平台CAD制图、PCB电路板、IC我知道了、HDL硬件描述语言叙述、电路仿真和设计软件,元素分析表

    中国澳门sinox很多平台CAD制图.PCB电路板.IC我知道了.HDL硬件描述语言叙述.电路仿真和设计软件,元素分析表,可打开眼世界. 最近的研究sinox执行windows版protel,powe ...

  5. Log4jdbc demo

    package log4jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import org.junit.Te ...

  6. 【iOS】MD5数据加密和网络安全

    在做网络应用程序时,, 始终把确保用户数据的安全性, 因此要加密. MD5算法在国内用的非常多.  MD5算法的特点: *相同的数据加密结果是一样的.(32个字符) *不可逆的.(不能逆向解密) *可 ...

  7. Ubuntu 14.04 LAMP搭建(Apache 2.47+MySQL 5.5+PHP5.5)

    原文:Ubuntu LAMP搭建 为了数据库课程设计,只好自己搭一个数据库系统,采用LAMP方式. 一.安装 1.安装Apache sudo apt-get install apache2 Apach ...

  8. 控制执行流程——(Java学习笔记三)

    if-else     控制程序流程最基本的形式 格式: if(boolean - expresion){ statement } 或 if(boolean - expresion){ stateme ...

  9. [Network]Introduction and Basic concepts

    [该系列是检讨计算机网络知识.因为现在你想申请出国.因此,在写这篇博客系列的大多数英语.虽然英语,但大多数就是我自己的感受和理解,供大家学习和讨论起来] 1 Network Edge The devi ...

  10. 框架搭建资源 (二) 添加M(模型)

    applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xm ...