题目:

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. 洛谷 P3830 [SHOI2012]随机树

    https://www.luogu.org/problemnew/show/P3830 具体方法见代码.. 其实挺神奇的,概率可以先算出“前缀和”(A小于等于xxx的概率),然后再“差分”得到A恰好为 ...

  2. 开源GIS-对比GeoServer和MapServer

    1  主流组合: 基于C.C++系列的:Mapserver(服务器)+QGIS(桌面软件)+PostGIS(数据库)+Openlayers(JS)/ openscale (FLex)(浏览器客户端) ...

  3. React 实践记录 01 组件开发入门

    Introduction 本文组成: Ryan Clark文章Getting started with React的翻译. 博主的实践心得. React由Facebook的程序员创建,是一个非常强大的 ...

  4. Ubuntu 14.04 安装深度音乐的方法(下载速度极慢未成功)

    原文地址:http://tieba.baidu.com/p/3023784357 由于14.04未提供gstreamer0.10-ffmpeg导致很多人安装深度音乐失败... 这里是安装方法: 1. ...

  5. 洛谷 P1201 [USACO1.1]贪婪的送礼者Greedy Gift Givers

    贪婪的送礼者Greedy Gift Givers 难度:☆ Code: #include <iostream> #include <cstdio> #include <c ...

  6. 安卓4.4不支持touchend事件解决办法

    最近的项目要求兼容到OPPO A31这款手机,这款手机是安卓4.4,调试时遇到了touch手指不能滑动页面切换的问题,最终解决通过在touchstart事件里面加上一个 event.preventDe ...

  7. LR中排序脚本

    /* * LoadRunner Java script. (Build: 670) * * Script Description: * */ import lrapi.lr; public class ...

  8. 你不知道的HTTP之HTTPS

    确保web安全的HTTPS HTTPS=HTTP+ 加密 + 认证 + 完整性保护 1.加密: 1)通信的加密 所谓互联网,是由能连通到全世界的网络组成的.无论世界哪个角 落的服务器在和客户端通信时, ...

  9. POJ 2831 Can We Build This One?

    Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 1728   Accepted: 643 Case Time Limit: 2 ...

  10. UVA - 658 It's not a Bug, it's a Feature! (隐式图的最短路,位运算)

    隐式的图搜索,存不下边,所以只有枚举转移就行了,因为bug的存在状态可以用二进制表示,转移的时候判断合法可以用位运算优化, 二进制pre[i][0]表示可以出现的bug,那么u&pre[i][ ...