题目

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. Angular CLI的简单使用(2)

    刚才创建了myApp这个项目,看一下这个项目的文件结构.    项目文件概览 Angular CLI项目是做快速试验和开发企业解决方案的基础. 你首先要看的文件是README.md. 它提供了一些如何 ...

  2. EEC 欧姆龙PLC输入模块算法

        Option Explicit Public MyArray(20000) As Integer Public MyArraySensor(20000) As Integer Sub 生成输入 ...

  3. 三种zigbee网络架构详解

    在万物互联的背景下,zigbee网络应用越加广泛,zigbee技术具有强大的组网能力,可以形成星型.树型和网状网,三种zigbee网络结构各有优势,可以根据实际项目需要来选择合适的zigbee网络结构 ...

  4. COGS 1365. [HAOI2013] 软件安装

    ★★☆   输入文件:haoi13t4.in   输出文件:haoi13t4.out   简单对比时间限制:1 s   内存限制:128 MB Dr.Kong有一个容量为N MB (1 <= N ...

  5. IP地址与数字地址相互转换

    /// <summary> /// IP地址转换成数字 /// </summary> /// <param name="addr">IP地址&l ...

  6. MovieReview—Avengers: Infinity War(复仇者联盟3:无限战争)

    Antagonist? Thanos,the central figure of the Avengers 3,antagonist. Everyone has his own ideals and ...

  7. noip模拟赛#39

    昨晚打开的题想了一会发现都不会后决定慢慢想.然后早上开校会的时候莫名其妙的都想出来了... T1:m=100,ai=50000,i<=5.1到m的数每个数只能用一次,判断是否能够有这些数的某些数 ...

  8. 使用pip 提示UnicodeDecodeError: 'ascii' codec can't decode解决方法

    python目录 Python27\Lib\site-packages 建一个文件sitecustomize.py 内容写: import sys sys.setdefaultencoding('gb ...

  9. InstallShield Limited Edition for Visual Studio 2013 图文教程打包安装包

    http://www.wuleba.com/23892.html 从Visual Studio 2012开始,微软就把自家原来的安装与部署工具彻底废掉了,转而让大家去安装使用第三方的打包工具“Inst ...

  10. vue列表过渡效果

    <transition-group></transition-group> ① 列表 <transition-group> </transition-grou ...