Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题目的意思是:要在一个数组里面找出两个数,使得他们相加的和等于给定的数,输出两个数的在数组里面对应的索引。
Solution
最基本的思路是穷竭搜索(暴搜),两重循环,时间复杂度O(n^2);这个方法会造成Time Limited Exceed,测试用例是个很大的一维数组。
更好的办法是使用map: 可以达到O(n)的时间复杂度。记忆化搜索,遍历数组时,先在map里面查询target-num(和减去当前的数字),如果没有找到,则将当前数字(做为key)和对应的数组索引(做为value)保存在map中,如果找到了,则直接输出。
这里选择STL里面的unordered_map作为map数据结构的实现。
Code
/**
* Leetcode problem list 1: two sum.
* Use map algorithm(stl).
*
* hellfire(asyncloading#163.com)
* Feb 15th, 2016
*/
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> output(2);
unordered_map<int, int> umap;
for (int i = 0; i < nums.size(); i ++)
{
if (umap.find(target - nums[i]) != umap.end())
{
output[0] = umap[target - nums[i]];
output[1] = i;
}
else
{
umap.insert(make_pair(nums[i], i));
}
}
return output;
}
};
int main(int argc, char **argv)
{
Solution s;
int arr[] = {2, 7, 11, 15};
int target = 13;
vector<int> nums(arr, arr + 3);
vector<int> output = s.twoSum(nums, target);
cout << output[0] << output[1] << endl;
}
源代码对应的Github地址: https://github.com/oj-problem/leetcode/blob/master/solution1.cpp
备注
c++语法:不能直接将数组赋值给vector容器,可以采用下面的方式。
int arr[] = {2, 7, 11, 15};
vector<int> nums(arr, arr + 3);