题目

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) {
std::vector<int> ret_vector;
std::map<int,int> value_index;
for (int i = ; i < numbers.size(); ++i)
{
const int gap = target - numbers[i];
if (value_index.find(gap) != value_index.end())
{
ret_vector.push_back(std::min(i+,value_index[gap]+));
ret_vector.push_back(std::max(i+,value_index[gap]+));
break;
}
else
{
value_index[numbers[i]] = i;
}
}
return ret_vector;
}
};

Tips:

元素无序且要求复杂度O(n)的,就可以用hashmap解决。

网上有的算法先遍历一遍numbers获得所有元素的map<value,index>,再进行后续的计算。这样的算法没有考虑数组元素重复的case

比如:

numbers = [0,2,4,0]

target = 0

===========================================

第二次过此题,大体思路非常明确。额外开一个hashmap,访问数组一次就搞定。

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
unordered_map<int, int> value_index;
for ( int i=; i<nums.size(); ++i )
{
if ( value_index.find(target-nums[i])!=value_index.end() )
{
ret.push_back(i+);
ret.push_back(value_index[target-nums[i]]+);
break;
}
value_index[nums[i]] = i;
}
std::sort(ret.begin(), ret.end());
return ret;
}
};

tips:

有三个细节需要注意:

1. [3, 2, 4] 6 对于这种类型的,一定要把value_index[nums[i]]=i放在if语句的后面,要不然同一个元素3就被用了两次

2. 题目要返回的index并不是数组下标,而是数组下标加1,且返回的值要求有序

【Two Sum】cpp的更多相关文章

  1. 【Path Sum】cpp

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

  2. 【Combination Sum 】cpp

    题目: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C  ...

  3. 【Binary Tree Maximum Path Sum】cpp

    题目: Given a binary tree, find the maximum path sum. The path may start and end at any node in the tr ...

  4. 【Minimum Path Sum】cpp

    题目: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right w ...

  5. 【二叉树的递归】03判断二叉树中有没有和为给定值的路径【Path Sum】

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 给定一个二叉树和一个和,判断这个树 ...

  6. 【Add binary】cpp

    题目: Given two binary strings, return their sum (also a binary string). For example,a = "11" ...

  7. hdu 4739【位运算】.cpp

    题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...

  8. Hdu 4734 【数位DP】.cpp

    题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...

  9. POJ 1018 【枚举+剪枝】.cpp

    题意: 给出n个工厂的产品参数带宽b和价格p,在这n个工厂里分别选1件产品共n件,使B/P最小,其中B表示n件产品中最小的b值,P表示n件产品p值的和. 输入 iCase n 表示iCase个样例n个 ...

随机推荐

  1. 在SQL中查看文件组中有哪些表

    SELECT o.[name], o.[type], i.[name], i.[index_id], f.[name] FROM sys.indexes i INNER JOIN sys.filegr ...

  2. HDU3308 线段树区间合并

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3308 ,简单的线段树区间合并. 线段树的区间合并:一般是要求求最长连续区间,在PushUp()函数中实 ...

  3. 如何在SAP Cloud for Customer自定义BO中创建访问控制

    文章作者: Yi 已获得Yi的转载许可. 访问控制方式和使用注意事项 1. C4C中的访问控制有两种方式 RelevantForAccessControl AccessControlContext 2 ...

  4. js高级笔录

    1.类型转换①转换成字符串toString() ⅰBoolean 值.数字和字符串的原始值的有趣之处在于它们是伪对象,这意味着它们实际上具有属性和方法. var sColor = "red& ...

  5. python_27_多级字典嵌套及操作

    #key-value 字典无下标 所以乱序,key值尽量不要取中文 person_log={ '大二':{ 'Ya Nan':['free','cute','soso'], 'Sha sha':['微 ...

  6. Windows环境下在Oracle VM VirtualBOX下克隆虚拟机镜像(克隆和导入)

    Windows环境下在Oracle VM VirtualBOX下克隆虚拟机镜像: 注:直接复制一个.vdi 虚拟硬盘再挂上去就可以,但Virtualbox居然提示UUID重复,无法使用. 则,可以通过 ...

  7. CUDA && GPU中dim3介绍

  8. Andrew NG 自动化所演讲(20140707):DeepLearning Overview and Trends

    出处 以下内容转载于 网友 Fiona Duan,感谢作者分享 (原作的图片显示有问题,所以我从别处找了一些附上,小伙伴们可以看看).最近越来越觉得人工智能,深度学习是一个很好的发展方向,应该也是未来 ...

  9. 分词,复旦nlp,NLPIR汉语分词系统

    http://www.nlpir.org/ http://blog.csdn.net/zhyh1986/article/details/9167593

  10. sass安装更新及卸载方法

    在 Windows 平台下安装 Ruby 需要先有 Ruby 安装包,大家可以到 Ruby 的官网(http://rubyinstaller.org/downloads)下载对应需要的 Ruby 版本 ...