题目

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. zblog删除网站后台顶部菜单中的“官方网站”链接

    文件\zb_system\function\c_system_admin.php 注释或删除代码 $topmenus[] = MakeTopMenu("misc", $zbp-&g ...

  2. SpringBoot常用应用属性配置表

    #========================================= #COMMON SPRING BOOT PROPERTIES # #This sample file is pro ...

  3. ADO.net数据访问方法

    ADO.NET是一组用于和数据源进行交互的面向对象的类库. 核心组件有两个: DataSet 是 ADO.NET 的非连接(断开)结构的核心组件.DataSet 的设计目的很明确:为了实现独立于任何数 ...

  4. POJ 3280 Cheapest Palindrome(区间dp)

    dp[i][j]表示处理完i到j的花费,如果s[i] == s[j] 则不需要处理,否则处理s[i]或s[j], 对一个字符ch,加上ch或删掉ch对区间转移来说效果是一样的,两者取min. #inc ...

  5. Nginx源码安装及调优配置(转)

      导读 由于Nginx本身的一些优点,轻量,开源,易用,越来越多的公司使用nginx作为自己公司的web应用服务器,本文详细介绍nginx源码安装的同时并对nginx进行优化配置. Nginx编译前 ...

  6. 2017.12.24 Java序列化你不知道的事(二)

    1 序列化允许重构 序列化允许一定数量的类变种,甚至重构之后也是如此,ObjectInputStream 仍可以很好地将其读出来. Java Object Serialization 规范可以自动管理 ...

  7. python_33_文件操作2

    f=open('yesterday',encoding='utf-8') #print(f.readline())#读一行,并且是第一行 #读前5行 for i in range(5):#range( ...

  8. Java不同对象之间复制属性

    // 导入包import org.springframework.beans.BeanUtils; /** * 调用工具复制2个对象之间的属性 2个JavaBean对象复制的属性名相同 * @para ...

  9. Pots POJ - 3414 (搜索+记录路径)

    Pots Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 22688   Accepted: 9626   Special J ...

  10. 爬虫学习(九)——登录获取cookie爬取

    import urllib.requestimport urllib.parseimport http.cookiejar # http.cookiejar 该包是专门对网页的cookie只进行获取的 ...