题目:

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. 牛客寒假5-I.炫酷镜子

    链接:https://ac.nowcoder.com/acm/contest/331/I 题意: 小希拿到了一个镜子块,镜子块可以视为一个N x M的方格图,里面每个格子仅可能安装`\`或者`/`的镜 ...

  2. CSS浮动float父div没有高度的问题

    如下所示,子元素 div2 本身具有高度和宽度,但由于其具有float:left:属性后.其父元素 div1 不具有高度. <html>    <head>    </h ...

  3. 左右两个Select列表框交换数据的JS

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD ...

  4. 谈PHP中的钩子

    钩子,英文为hooks.在程序中应用相当广泛,但是究竟什么是钩子呢?本人介绍一下目前本人对钩子的理解和相关心得. 假如有这么一段程序流: function fun(){ funA(); funB(); ...

  5. Linux 安装gcc4.8版本

    1.下载安装包 http://ftp.tsukuba.wide.ad.jp/software/gcc/releases/gcc-4.8.1/ 2.解压 .tar.gz 3.下载编译所需的依赖包 cd ...

  6. CImage访问像素及其像素操作总结

    MSDN的代码 COLORREF pixel; int maxY = imgOriginal.GetHeight(), maxX = imgOriginal.GetWidth(); byte r,g, ...

  7. ruby 正则匹配返回值matchdata

    引用连接: 为处理与正则表达式的匹配过程相关的信息而设置的类. 可以通过下列途径 Regexp.last_match Regexp#match, String#match $~ 得到该类的实例. 超类 ...

  8. Gin框架body参数获取

    需求: 记录所有请求的json数据 body, _ := ioutil.ReadAll(c.Request.Body) if body != nil { log.Info("请求body内容 ...

  9. java 并发容器一之BoundedConcurrentHashMap(基于JDK1.8)

    最近开始学习java并发容器,以补充自己在并发方面的知识,从源码上进行.如有不正确之处,还请各位大神批评指正. 前言: 本人个人理解,看一个类的源码要先从构造器入手,然后再看方法.下面看Bounded ...

  10. 将生成的Excel表发送到邮箱

    本文接上一篇,将得到的Excel表发送到邮箱.. 在上一篇中,本人使用的是直接从数据库中获取数据,然后包装成Excel表.现在将该Excel表发送到目的邮箱,如果需要跟上篇一样,定时每天某时刻发送,就 ...