题目:

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. scrapy框架中Item Pipeline用法

    scrapy框架中item pipeline用法 当Item 在Spider中被收集之后,就会被传递到Item Pipeline中进行处理 每个item pipeline组件是实现了简单的方法的pyt ...

  2. python 基础(五) 迭代器与生成器

    迭代器和生成器 迭代器 iterator (1) 迭代对象: 可以直接作用于for循环的 称为可迭代对象(iterable)可以通过 isinstance 判断是否属于可迭代对象 可以直接作用于for ...

  3. 19 标签:xml或者html

    1       标签:xml或者html 1.1  使用XmlSlurper解析xml groovy处理xml非常容易.XmlSlurper 类用来处理xml.在处理xml方面,还有其他的处理方式,但 ...

  4. 牛客网Java刷题知识点之什么是死锁、死锁产生的4个必要条件、死锁的解除与预防

    不多说,直接上干货! https://www.nowcoder.com/ta/review-java/review?query=&asc=true&order=&page=16 ...

  5. net core 在docker(ubuntu)部署

    1.vs新建项目并发布,然后copy到linux系统上,我这里是用的虚拟机. 2 Dockerfile文件配置 FROM microsoft/dotnet:2.1-aspnetcore-runtime ...

  6. echarts 添加Loading 等待。

    capturedsDetailsEcharts: function(id) { if (!id) { id = mini.get("chnNameCaptureds").getVa ...

  7. body和普通div背景图宽高百分比的区别

    body和普通div背景图的区别  background: url(//m.360buyimg.com/mobilecms/s220x220_jfs/t2746/167/831241799/29915 ...

  8. hihocoder1829 Tomb Raider

    思路: 暴力枚举. 实现: #include <iostream> #include <set> #include <vector> using namespace ...

  9. JavaScript30-7 数组的一些基本方法

    本次来学习数组的一些方法,之前学习的js数组的方法是在第四课里面(没有写到随笔里面) 之前第四课主要讲的是 filter() ,map() 这次课程主要介绍的是 some()`.`every()`.` ...

  10. Glide图片框架

    //加载圆形图片Glide.with(this).load(WSCAppStatic.WEB_KEFU_PHOTO_URL+ "?usercode=8120000315") .as ...