题目:

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

分析:

该题目标记为Medium,难度为中等,阅读题目后,第一反应便是两次遍历数组,些许判断便可解决。然后三下五除二写下了代码,信心满满提交:
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers , int target)
{
vector<int> index;
for(int i=0 ; i!=numbers.size(); i++)
{
for(int j=numbers.size()-1 ; j>i; j--)
if((numbers[i]+numbers[j]) == target)
{
index.push_back(i+1);
index.push_back(j+1);
break;
} }//for
return index;
}//twoSum
};
没错,想嘛,堂堂LeetCode中等难度的题目,就这样可以AC的话岂不是。。。于是,我就得到了这样的回应:
Status:

Time Limit Exceeded

再次分析:

重新审视题目,上面提供的O(n^2)的算法肯定达不到要求,到底应该用什么方式可以避免重叠循环,思来想去还是没有答案,最终还是只能求助百度了。当扫到一网友的分析后,恍然大悟,我们学习哈希干嘛的呀,就是因为它有着与生俱来的复杂度的优势。
废话不多说,下面提供AC代码:
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers , int target)
{
vector<int> index;
map<int , int> hashMap;
for(unsigned int i=0 ; i<numbers.size(); i++)
{
if(!hashMap.count(numbers[i]))
hashMap.insert(make_pair(numbers[i] , i));
if(hashMap.count(target-numbers[i]))
{
int pos = hashMap[target-numbers[i]];
if(pos < i)
{
index.push_back(pos+1);
index.push_back(i+1);
}
}//if
}//for
return index;
}//twoSum
};
这样,算法复杂度就降到了O(n),顺利AC了我的第一个LeetCode题目。
看来,自己还是水到家了,还需要继续努力!

测试main函数:

为了方便程序测试,这儿也提供main函数的代码,供于参考:
int main()
{
Solution s;
int arr[3] = {3,2,4};
int target = 6;
vector<int> numbers(arr , arr+3);
vector<int> index;
index = s.twoSum(numbers , target); cout<<"index1="<<index[0]<<", index2="<<index[1]<<endl;
return 0;
}

LeetCode01 AC代码下载


LeetCode(1)Two Sum的更多相关文章

  1. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

  2. LeetCode(307) Range Sum Query - Mutable

    题目 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclus ...

  3. LeetCode(304)Range Sum Query 2D - Immutable

    题目 Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper ...

  4. LeetCode(303)Range Sum Query - Immutable

    题目 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclus ...

  5. LeetCode(112) Path Sum

    题目 Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

  6. LeetCode(40) Combination Sum II

    题目 Given a collection of candidate numbers (C) and a target number (T), find all unique combinations ...

  7. LeetCode(39) Combination Sum

    题目 Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C w ...

  8. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  9. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

随机推荐

  1. GYM 101673F(树计数)

    树上每个割点计算一下各个size的组合相乘再相加为第一问答案,取最大的:再把本答案中最大的两个size相乘减掉,为第二问答案. const int maxn = 1e4 + 5; int n, siz ...

  2. 洛谷P4095||bzoj3163 [HEOI2013]Eden 的新背包问题

    https://www.luogu.org/problemnew/show/P4095 不太会.. 网上有神奇的做法: 第一种其实是暴力(复杂度3e8...)然而可以A.考虑多重背包,发现没有办法快速 ...

  3. python之生成器(~函数,列表推导式,生成器表达式)

    一.生成器 概念:生成器的是实质就是迭代器 1.生成器的贴点和迭代器一样,取值方式也和迭代器一样. 2.生成器一般由生成器函数或者声称其表达式来创建,生成器其实就是手写的迭代器. 3.在python中 ...

  4. nodejs 学习(1) http与fs

    var http=require("http"), fs=require('fs'); var server=http.createServer(function(req,res) ...

  5. MySql下载地址

    因为下载mysql需要注册,很麻烦,记录下下载地址: My sql 5.1.71 http://cdn.mysql.com/Downloads/MySQL-5.1/mysql-5.1.71-win32 ...

  6. hdu2475Box(splay树形转线性)

    链接 推荐一篇帖子 http://blog.csdn.net/lyhypacm/article/details/6734748 这题暴力不可行主要是因为这颗树可能极度不平衡,不能用并查集是不能路径压缩 ...

  7. 使用nginx+tomcat实现静态和动态页面的分离

    博主最近在优化一个javaweb项目,该项目之前一直都是使用tomcat处理用户请求的,无论静态还是动态的东西,一律交给tomcat处理.tomcat主要是负责处理servlet的,静态的文件还是交给 ...

  8. 《深入理解JavaScript闭包和原型》笔记

    By XFE-堪玉 以下知识来源于对王福朋所写<深入理解javascript原型和闭包>的理解和整理 一切都是对象[引用类型],对象都是通过函数创建的[Funcion类型] 对象是属性的集 ...

  9. UVALive 3211 Now or Later (2-SAT)

    题目的要求一个最小值最大,二分即可,但是怎么判断呢? 飞机早或者晚两种状态,可以用一个布尔变量表示,假设当前猜测为m,那么根据题意, 如果x和y所对应的时间冲突那么就是¬(xΛy)化成或的形式(¬x) ...

  10. x+2y+3z=n非负整数解

    #include <iostream> #include <string.h> #include <stdio.h> using namespace std; ty ...