问题描述
对于一个给定的数组,找出2个数,它们满足2个数的和等于一个特定的数,返回这两个数的索引。(从1开始)
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
解决方案
1.思路分析:
我们将求2个数的索引转换成在数组中搜索(target-nums[i])的位置;
直观想,两层遍历,固定一个元素,循环右移另一个元素,逐个测试,时间复杂度$O(n^2)$,而$O(n^2)$一般不能接受,因此需要考虑改进算法:
想法则是降低到$O(n\ lgn)$,最理想则是$O(n)$
2.测试样例:
正数、负数、0
3.特殊情况:
数组不足2个数、两数相加溢出、没有匹配的情况
4.实现
4.1 两层遍历的实现:O(n2)
#include <iostream>
using namespace std;
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
returnSize = NULL;
if (numsSize < 2)
return returnSize;
int i = -1;
int j;
while (++i < numsSize-1) {
if (nums[i] >= target)
continue;
j = i;
while (++j < numsSize) {
compare_times++;
if (nums[i] + nums[j] == target)
break;
}
if (j == numsSize)
continue;
else
break;
}
if (i != numsSize-1) {
returnSize = new int [2];
returnSize[0] = i+1;
returnSize[1] = j+1;
}
return returnSize;
}
int main()
{
int nums[] = {-1, 0, 9, 5, 7, 11, 15, 20};
int target = 9;
int *index = NULL;
index = twoSum(nums, sizeof(nums)/sizeof(nums[0]), target, index);
if(index != NULL)
cout<<"index1 = "<<index[0]<<", index2 = "<<index[1]<<endl;
}
提交到leetcode 返回Time Limit Exceeded,不满足时间要求。
4.2 排序实现 O(n lgn)
首先将数组进行快速排序或者插入到二叉搜索树中,二分查找,当固定一个元素nums[i],在数组中查找target - nums[i],此时查找时间降低到O(lg n),总消耗即为O(n lgn)
4.3 线性实现-Hash表 O(n)
我们知道对元素的搜索最快则是O(1),即直接索引到,联想只能是Hash表或者是关键字索引。关键字索引(从最小到最大)会占用额外的内存空间。
由于C++有现成的hash map,所以直接采用c++。
另外我们要求的是元素的索引,即Hash表的关键字,所以我们把数组元素作为Hash表的关键字,而把数组元素的索引作为Hash表的元素值。
class Solution
{
public:
vector<int> twoSum(const vector<int> &nums, int target) {
vector<int> results;
if (nums.size() < 2) {
return results;
}
map <int , int> hmap;
//插入到hash map
for (int i = 0; i < nums.size(); i++) {
hmap.insert(pair <int, int> (nums[i], i) ); //元素值做关键值
}
int j;
for (int i = 0; i < nums.size(); i++) {
//hmap.count(x):x在hash map中出现的次数
if (hmap.count(target - nums[i])) {
j = hmap[(target - nums[i])];
if (j < i) {
results.push_back(j+1);
results.push_back(i+1);
}
}
}
return results;
}
};
测试
int main()
{
int nums[] = {0,-3, 2, 7, 11, 15, 20};
vector<int> nums_v(nums, nums+7);
int target = 9;
while (1) {
class Solution sol;
vector<int> results = sol.twoSum(nums_v, target);
if(results.size())
cout<<"index1 = "<<results[0]<<", index2 = "<<results[1]<<endl;
}
getchar();
}