题目

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. 逐步解读String类(一)

    一句题外话 面试刚入行的Java新手,侧重基础知识:面试有多年工作经验的老鸟,多侧重对具体问题的解决策略. 从一类面试题说起 考察刚入行菜鸟对基础知识的掌握程度,面试官提出关于String类的内容挺常 ...

  2. 飞塔NGFW-FortiGate-5.2(BYOL)

    平台: FortiGate 类型: 虚拟机镜像 软件包: basic software FortiGate ips security UTM vpn 反垃圾邮件 网页过滤 服务优惠价: 按服务商许可协 ...

  3. sql server 搭建发布订阅后,改端口不正常工作的问题

    sql 的发布订阅,想必大家都了解,但一般都是在默认的1433的情况下搭建的,那么1433换成别的端口,发布还能正常工作吗? 在一次客户的真实场景上我就遇到了. 好了,今天不想写太多,简化下, 测试环 ...

  4. 实战:ADFS3.0单点登录系列-集成Exchange

    本文将介绍如何将Exchange与ADFS集成,从而实现对于Exchange的SSO. 目录: 实战:ADFS3.0单点登录系列-总览 实战:ADFS3.0单点登录系列-前置准备 实战:ADFS3.0 ...

  5. 【51nod1677】treecnt(树上数学题)

    点此看题面 大致题意: 给你一个节点从1~n编号的树,让你从中选择k个节点并通过选择的边联通,且要使选择的边数最少,让你计算对于所有选择k个节点的情况最小选择边数的总和. 题解 这道题乍一看很麻烦:最 ...

  6. Matlab将多幅图片保存为mat

    %% 储存某目录所有的图片 pt = 'd:\imgs\'; ext = '*.jpg'; dis = dir([pt ext]); nms = {dis.name}; for k = 1:lengt ...

  7. angular4 学习日志(一 依赖注入)

    1.创建一个服务,为了好管理建一个名叫services的文件夹管理所有服务: ng g service services\person 2.在服务中定义一个person 类 : 3.在app.mdul ...

  8. 查询Linux下已安装软件的版本

    #rpm -qa | grep mysql

  9. C#条件运算符(?:)

    一.C#条件运算符(?:) 条件运算符(?:),有时也称为三元操作符“?:”.它是根据布尔型表达式的值返回?后面的两个值中的一个.如果条件为True,则计算第一个表达式并以它的计算结果为准:如果条件为 ...

  10. 【原创】大数据量时生成DataFrame避免使用效率低的append方法

      转载请注明出处:https://www.cnblogs.com/oceanicstar/p/10900332.html      ★append方法可以很方便地拼接两个DataFrame df1. ...