题目:

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. 洛谷P2505||bzoj2750 [HAOI2012]道路 && zkw线段树

    https://www.luogu.org/problemnew/show/P2505 https://www.lydsy.com/JudgeOnline/problem.php?id=2750 神奇 ...

  2. 异步加载js文件的方法

    # 异步加载js文件 - js的加载默认是同步的,因为js是单线程执行,只能完成一件再执行下一件. - 一些外部引入的js文件可以因为文件太大,在加载资源的过程中会影响dom元素的加载,影响了用户体验 ...

  3. Excel 通过pl/sql导入到数据库 文本导入器 odbc导入器

     Excel 通过pl/sql导入到数据库 第一种方法:文本导入器 1.准备Excel导入数据   jc.xls 2.把 jc.xls 文件 改为 jc.csv文件 3.在数据库里建一张jc表(FLH ...

  4. IDEA自定义设置快捷键输出你想要的语句!

    转载,侵权必删 用Eclipse时间长了, 就习惯之前的快捷键! 当然, IDEA不愧是Java开发的”利器”! 写起代码就是一个字 – “爽”! 建议大家可以去尝试一下! 当然, 在IDEA中输出S ...

  5. aspx页面调用webapi接口报错:远程服务器返回错误:(500)内部服务器错误

    代码在运行到response = (HttpWebResponse)request.GetResponse();就开始报错 原因:可能因为所调用的接口不存在或者接口中存在错误,可用postman测试接 ...

  6. 洛谷 P3853 [TJOI2007]路标设置

    路标设置 二分枚举"空旷指数", 做法与跳石头类似. #include <iostream> #include <cstdio> #include < ...

  7. jQuery选择器之样式二

    prop()方法和attr()类似,但是HTML5规定有一种属性在DOM节点中可以没有值,只有出现与不出现两种,例如: <input id="test-radio" type ...

  8. Sql 行转换为列 以及列转换为行的心得

    这是 创建数据库的脚本文件 CREATE TABLE [dbo].[stu]( [学号] [nvarchar](255) NOT NULL, [姓名] [nvarchar](255) NULL, [性 ...

  9. block 应用说明

    一.Block定义 Block可以理解为一个函数指针(即它是一个指针,指向某个函数) returnType (^blockName) (parameter list) = ^ (parameter l ...

  10. [文章泛读] The varying faces of a program transformation systems (ACM Inroads, 2012)

    Beevi S. Nadera, D. Chitraprasad, and Vinod S. S. Chandra. 2012. The varying faces of a program tran ...