题目:

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. CSS3学习笔记——伪类hover

    最近看到一篇文章:“Transition.Transform和Animation使用简介及应用展示”    ,想看看里面 “不同缓动类效果demo”例子的效果,发现了一个问题如下: .Trans_Bo ...

  2. 用Eclipse运行Android版APP(PhoneGap)时出现:Unable to execute dex: Multiple dex files define

    这两天遇到点小问题,做个记录: 症状:运行,调试时都报:Unable to execute dex: Multiple dex files define错误,发布后的APP安装到手机后一运行,就提示: ...

  3. Hadoop - Azkaban 作业调度

    1.概述 在调度 Hadoop 的相关作业时,有以下几种方式: 基于 Linux 系统级别的 Crontab. Java 应用级别的 Quartz. 第三方的调度系统. 自行开发 Hadoop 应用调 ...

  4. SAP ECC CO 配置

    SAP ECC 6.0 Configuration Document Controlling (CO) Table of Content TOC \o \h \z 1. Enterprise Stru ...

  5. C# vs MySql

    MySqlHelper类 /// <summary> ///MySql操作类 /// </summary> public abstract class MySqlHelper ...

  6. UFT\QTP 12 新特性

    UFT\QTP 12 新特性 http://blog.csdn.net/testing_is_believing/article/details/22310297

  7. DotNetBar RibbonControl控件office2007风格

    在使用DotNetBar RibbonControl控件的时候如果想吧效果做成下图这种效果 把主窗体继承Office2007RibbonForm 然后要删除删除styleManager1 才会出现上图 ...

  8. MMO之禅(二)职业精神

    MMO之禅(二)职业精神 --心态 目标 信仰 Zephyr 201304 继续上篇,继续讲什么?打了很多腹稿点滴,从引擎架构,到上层数据.逻辑模块规划,想了很多,临起笔,却总发觉四顾心茫然,乱不可言 ...

  9. EDM营销之双十一最新实战营销指南汇总

    双十一虽已进入第八个年头,但其影响力只增不减,倒计时期间商家们都已火力全开.再结合全社会消费升级的大背景,如何才能在激烈竞争中杀出一条血路呢? 本次Focussend基于实战操作,以短信营销.邮件营销 ...

  10. 在 Ubuntu 配置 PPTP Server

    本文在 Ubuntu 12.4 或 14 亲测有效. 建立 PPTP 服务器 首先安装 pptp 服务器. # apt-get install pptpd 然后配置 pptpd. # sudo vi ...