题目:

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

解题思路:

这道题,很容易想到的就是先排序,在通过两前后指针,向中间靠拢。当两指针所指元素之和与target相等时,则可返回。这里指的注意的是,因为排序后各元素下标会打乱,所以应该构造一个结构体,包含要排序的元素值及最原始的下标。因为要用到排序,所以时间复杂度为O(nlogn)。

第二种思路就是,利用哈希表解决,因为哈希表查找时间复杂度为O(1),当处理一个元素时,判断target-cur是否在哈希表中,在这返回结果即可,这种解法的时间复杂度为O(n)。

实现代码:

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std; /**
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 */
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> resvec(2, 0);
if(numbers.empty())
return resvec;
unordered_map<int, int> imap;
int len = numbers.size();
// for(int i = 0; i < len; i++)
// imap[numbers[i]] = i+1;
for(int i = 0; i < len; i++)
{
//这里要注意,一开始,我直接利用数组元素初始化map,但会出现相同元素值覆盖的情况
if(imap.count(target - numbers[i]))
{
resvec[0] = imap[target - numbers[i]] + 1;
resvec[1] = i+1;
break;
}
imap[numbers[i]] = i; } return resvec; }
};
int main(void)
{
int arr[] = {2,7,11,15};
vector<int> numbers(arr, arr+4);
Solution solution;
vector<int> resvec = solution.twoSum(numbers, 9); vector<int>::iterator iter;
for(iter = resvec.begin(); iter != resvec.end(); ++iter)
cout<<*iter<<endl; return 0;
}

LeetCode1:Two Sum的更多相关文章

  1. LeetCode-1:Two Sum

    [Problem:1-Two Sum] Given an array of integers, return indices of the two numbers such that they add ...

  2. LeetCode 题解(一):Two Sum

    LeetCode : two sum 第一次写博客,算是熟悉这些编辑环境吧,本来是打算在csdn上用markdown写的,结果改了博客介绍就被关闭了,晕死...好了,话不多说,今天打算拿LeetCod ...

  3. 通过位运算求两个数的和(求解leetcode:371. Sum of Two Integers)

    昨天在leetcode做题的时候做到了371,原题是这样的: 371. Sum of Two Integers Calculate the sum of two integers a and b, b ...

  4. HDU1244:Max Sum Plus Plus Plus

    题目链接:Max Sum Plus Plus Plus 题意:在n个数中取m段数使得这m段数之和最大,段与段之间不能重叠 分析:见代码 //dp[i][j]表示前i个数取了j段的最大值 //状态转移: ...

  5. SQL-W3School-函数:SQL SUM() 函数

    ylbtech-SQL-W3School-函数:SQL SUM() 函数 1.返回顶部 1. SUM() 函数 SUM 函数返回数值列的总数(总额). SQL SUM() 语法 SELECT SUM( ...

  6. No.001:Two Sum

    问题: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  7. HDU 1024:Max Sum Plus Plus(DP)

    http://acm.hdu.edu.cn/showproblem.php?pid=1024 Max Sum Plus Plus Problem Description Now I think you ...

  8. leetcode:Path Sum (路径之和) 【面试算法题】

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

  9. Project Euler 83:Path sum: four ways 路径和:4个方向

    Path sum: four ways NOTE: This problem is a significantly more challenging version of Problem 81. In ...

随机推荐

  1. Python: 收集所有命名参数

    有时候把Python函数调用的命名参数都收集到一个dict中可以更方便地做参数检查,或者直接由参数创建attribute等.更简单的理解就是def foo(*args, **kwargs): pass ...

  2. dwz_bootstrap + thinkphp

    http://www.thinkphp.cn/code/936.html  回去继续学习 SuperWebSocket

  3. freemarker springmvc配置异常

    异常信息 java.lang.IllegalAccessError: tried to access method freemarker.ext.servlet.AllHttpScopesHashMo ...

  4. LoadRunner AJAX TruClient协议Tips and Tricks

    LoadRunner AJAX TruClient协议Tips and Trickshttp://automationqa.com/forum.php?mod=viewthread&tid=2 ...

  5. android私有文件夹的访问

    首先内部存储路径为/data/data/youPackageName/,下面讲解的各路径都是基于你自己的应用的内部存储路径下. 所有内部存储中保存的文件在用户卸载应用的时候会被删除. 一. files ...

  6. 【经验谈】XmlSerializer的坑

    XmlSerializer我想现在用的人可能不多了,大家都在用Json.我现在所在的公司依然在用,所以发现了这个坑.当然这个坑存在很久了只是没用过所以才发现. 事情是这样的,测试那边说系统偶尔会报找不 ...

  7. Domain Space

    Bluehost Register Page http://www.bluehost.com/track/weipengp

  8. Nutch插件系统

    Nutch 基本情况 Nutch 是 Apache 基金会的一个开源项目,它原本是开源文件索引框架 Lucene 项目的一个子项目,后来渐渐发展成长为一个独立的开源项目.它基于 Java 开发,基于 ...

  9. 一款基于HTML5的Web 3D开发工具

    在我们协助客户进行3D应用的开发过程中,客户遇到的最头疼的问题是如何在短时间内学会使用TWaver 3D引擎,以及使用TWaver 3D来创建和导入项目所需的各种3D业务模型.由于项目涵盖的行业繁多. ...

  10. VS2012未找到与约束ContractName...匹配的导出

    用VS2012创建ARCGIS插件项目时,提示“未找到与约束ContractName...匹配的导出”,此前一直都是正常的额 经查,发现是近期系统相关更新导致,解决办法有两种途径: 一是删除近期更新的 ...