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. Python实现MapReduce,wordcount实例,MapReduce实现两表的Join

    Python实现MapReduce 下面使用mapreduce模式实现了一个简单的统计日志中单词出现次数的程序: from functools import reduce from multiproc ...

  2. Python学习(七)面向对象 ——封装

    Python 类的封装 承接上一节,学了Student类的定义及实例化,每个实例都拥有各自的name和score.现在若需要打印一个学生的成绩,可定义函数 print_score() 该函数为类外的函 ...

  3. 创建带Mipmap的osg::Image

    我们常用osgDB::readImage或者osg::Image::allocateImage()方式创建Image对象, 跟深一步的带Mipmap的Image怎样创建呢? 偶然在分析osgParti ...

  4. 详解vue父组件传递props异步数据到子组件的问题

    案例一 父组件parent.vue // asyncData为异步获取的数据,想传递给子组件使用 <template> <div> 父组件 <child :child-d ...

  5. (转)一个非常好的akka教程

    akka系列文章目录 akka学习教程(十四) akka分布式实战 akka学习教程(十三) akka分布式 akka学习教程(十二) Spring与Akka的集成 akka学习教程(十一) akka ...

  6. 转:sublime2 官方网址

    1. sublime2 官方网址 http://www.sublimetext.com/2

  7. Cognos备份与恢复方案

    场景:早上来上班,突然发现COGNOS服务器挂掉了,比如硬盘彻底坏掉了,不能恢复了,那该怎么办?前提是肯定要有备份啊. 备份内容: A:FM模型备份OKB:Cognos内容库备份OK 恢复过程: 1: ...

  8. ambari 大数据安装利器

    https://www.ibm.com/developerworks/cn/opensource/os-cn-bigdata-ambari/

  9. [Algorithm] Reverse array of Chars by word

    For example we have: ["p", "r", "e", "f", "e", &qu ...

  10. vbox下安装centos (全部都是基于64位)

    1.首先提示说CPU内核不匹配,如下图: 于是查阅资料得知:64位CPU支持32位和64位,而要用64位内核,就需要主板支持,于是修改BIOS,在ADVANCE(高级)里,找到VT(也就是virtua ...