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 zero-based.

Notice

You may assume that each input would have exactly one solution

 
Example

numbers=[2, 7, 11, 15], target=9

return [0, 1]

Challenge

Either of the following solutions are acceptable:

  • O(n) Space, O(nlogn) Time
  • O(n) Space, O(n) Time

题意

给一个整数数组,找到两个数使得他们的和等于一个给定的数 target

你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 0 到 n-1

解法一:

 class Solution {
public:
/*
* @param numbers: An array of Integer
* @param target: target = numbers[index1] + numbers[index2]
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
vector<int> twoSum(vector<int>& nums, int target) {
// hash[i]表示nums中数值为i的下标
unordered_map<int, int> hash;
vector<int> result; // 一边循环每个数,一边加入hash表。
for (int i = ; i < nums.size(); i++) {
if (hash.find(target - nums[i]) != hash.end()) {
// target - nums[i]的下标更小,放在前面
result.push_back(hash[target - nums[i]]);
result.push_back(i);
return result;
}
hash[nums[i]] = i;
} // 无解的情况
result.push_back(-);
result.push_back(-);
return result;
}
};

使用万能的hash,参考@NineChapter 的代码

解法二:

 class Solution {
public:
/*
* @param numbers: An array of Integer
* @param target: target = numbers[index1] + numbers[index2]
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
vector<int> twoSum(vector<int> &numbers, int target) {
int len = numbers.size();
int i, j;
int flag = ;//flag作为找到答案后跳出的一个标记用变量
for (i = ; i < len; ++i) {
for (j = i + ; j < len; ++j) {
if (numbers[i] + numbers[j] == target) {
flag=;
break;
}
}
if (flag)
break;
} vector<int> ans;
ans.push_back(i);
ans.push_back(j); return ans;
}
};

暴力破解法,完全不推荐

56. Two Sum【easy】的更多相关文章

  1. 1. Two Sum【easy】

    1. Two Sum[easy] Given an array of integers, return indices of the two numbers such that they add up ...

  2. 170. Two Sum III - Data structure design【easy】

    170. Two Sum III - Data structure design[easy] Design and implement a TwoSum class. It should suppor ...

  3. 167. Two Sum II - Input array is sorted【easy】

    167. Two Sum II - Input array is sorted[easy] Given an array of integers that is already sorted in a ...

  4. 121. Best Time to Buy and Sell Stock【easy】

    121. Best Time to Buy and Sell Stock[easy] Say you have an array for which the ith element is the pr ...

  5. 661. Image Smoother【easy】

    661. Image Smoother[easy] Given a 2D integer matrix M representing the gray scale of an image, you n ...

  6. 485. Max Consecutive Ones【easy】

    485. Max Consecutive Ones[easy] Given a binary array, find the maximum number of consecutive 1s in t ...

  7. 561. Array Partition I【easy】

    561. Array Partition I[easy] Given an array of 2n integers, your task is to group these integers int ...

  8. 2. Trailing Zeros【easy】

    2. Trailing Zeros[easy] Write an algorithm which computes the number of trailing zeros in n factoria ...

  9. 160. Intersection of Two Linked Lists【easy】

    160. Intersection of Two Linked Lists[easy] Write a program to find the node at which the intersecti ...

随机推荐

  1. 在Ubuntu 13.04下的安装eclipse

    来源:http://www.cnblogs.com/lanxuezaipiao/p/3325628.html 一.eclipse安装过程 首先确保在安装eclipse之前已经安装好Java虚拟机 1. ...

  2. osglightpoint例子 [转]

    该例子演示了光点的效果,主要应用osgSim库中的LightPoint.LightPointNode. SequenceGroup.BlinkSequence,osgSim库属于仿真库,扩展库.应用o ...

  3. 修改SharePoint 2013中Search Topology时遇到的一些问题以及一些Tips

    这次操作在笔者的场中涉及到5台服务器, CA, APP2, APP3, APP4, APP5. 原本只有CA运行着Search Service Applicaiton, 现在想让APP2-5运行这项服 ...

  4. Vue组件开发实践之scopedSlot的传递

    收录待用,修改转载已取得腾讯云授权 导语 现今的前端开发都讲究模块化组件化,即把公共的交互和功能封装到一个个的组件之中,在开发整体界面的时候就能像搭积木一样快速清晰高效.在使用Vue开发我们的vhtm ...

  5. [Functional Programming] Unbox types with foldMap

    Previously we have seen how to use Concat with reduce: ), Sum(), Sum()] .reduce((acc, x) => acc.c ...

  6. 一次踩坑记录(使用rpc前后端分离服务总是注册不上)

    问题简述: 项目架构使用了前后端分离,使用rpc进行服务调用与注册,这里没有用dubbo之类的,仅仅用zookeeper,每次在启动项目时总是报错rpcException异常跟NPE异常,后台查看zo ...

  7. PHP如何使用免费在线客服插件

    1 你可以从以下网址下载http://www.hur.cn/Soft/2011/12448.html 2 解压并放到任意文件夹下 3 在安装之前,先在数据库中创建一个完整的数据库,因为待会儿安装完成之 ...

  8. org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'statisticalMapper' defined in file

    ::, [localhost-startStop-1] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFact ...

  9. Hadoop-1.2.1学习之Job创建和提交源码分析

    在Hadoop中,MapReduce的Java作业通常由编写Mapper和Reducer開始.接着创建Job对象.然后使用该对象的set方法设置Mapper和Reducer以及诸如输入输出等參数,最后 ...

  10. 如何配置 Oracle VirtualBox 中的客户机与物理机网络

    当你在 Oracle VirtualBox 虚拟机软件 中安装了各种操作系统时,你可能需要实现物理机与虚拟机之间的相互访问. 在这篇文章中,我们将会以最简单明了的方式来说明如何配置客户机与 Linux ...