题目:

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. IOS , plist 配置项说明

    本文转载至 http://blog.csdn.net/fengsh998/article/details/8307424 Key:Application can be killed immediate ...

  2. JAVA IO NIO

    http://www.cnblogs.com/handsome1013/p/4882862.html http://www.cnblogs.com/dolphin0520/ http://www.cn ...

  3. Ubuntu进不入系统,一直停留在ubuntu图标画面(转)

    Ubuntu进不入系统,一直停留在ubuntu图标画面(转) 在VMware中对Ubuntu进行“关闭电源”后,再次进入,一直停留在ubuntu的图标画面,无法进入系统了!网上也有别的网友碰到这个问题 ...

  4. 【Android】Kill Service

    花了一天时间对如何Android保证Service不被杀死研究了一下,我的手机是Nexus5,系统4.4.2. 杀死一个Service通常有以下几种可能: 1)APP自己杀死(包括调用stopServ ...

  5. easyui filebox 浏览图片

    <img id="image1"/> <input id="f1" class="easyui-filebox" name ...

  6. 解决访问StackOverFlow太慢的问题

    Stackoverflow加载时访问了被屏蔽的站点ajax.googleapis.com,导致加载缓慢,把这个站点加到Hosts里,指向127.0.0.1即可

  7. Windows Phone后台音乐播放本地代理实现讨论

    前一篇文章讨论的wp平台音乐播放的一些遇到的问题,经过苦思冥想和多方参考安卓实现:发现我们可以考虑一种本地代理的思想来完成我们的边听边存,并且流畅拖动进度条.希望大家一起讨论.可以下载我的代码一同研究 ...

  8. codeforces D. Design Tutorial: Inverse the Problem

    题意:给定一个矩阵,表示每两个节点之间的权值距离,问是否可以对应生成一棵树, 使得这棵树中的任意两点之间的距离和矩阵中的对应两点的距离相等! 思路:我们将给定的矩阵看成是一个图,a 到 b会有多条路径 ...

  9. [Python] Remote debugging by Pycharm

    From: http://blog.csdn.net/u013088062/article/details/50170551 虚拟环境配置 配置远程解释器 设想这样一种情况,你在一个平台上操作你的工程 ...

  10. linux主机间复制文件

    命令基本格式: 1.从 本地 复制到 远程    * 复制文件:          * 命令格式:                  scp local_file remote_username@re ...