在一个有序数组中,找出两个数,使得两数之和等于目标值。数组下标从1开始。
输入: numbers = [5,6,7,8,9,10], target = 11
输出: [1,2]
解释: 5 与 6 之和等于目标值 11 。因此 index1 = 1, index2 = 2 。
1.1解题思路
有三种常见解法,一种是暴露和哈希表,可以参考博主写的这篇博客https://blog.csdn.net/naibozhuan3744/article/details/104160305。本文主要总结用双指针法,解决这个问题。因为这是一个有序数组,所以可以用双端指针,分别取数据,具体步骤如下:
1.1.1双端指针指向数组起始pstart和末尾位置pend
1.1.2如果这两个指针指向的数相加和为目标值,则顺序输出;否则继续比较
1.1.3如果两数之和小于目标值,则指向较小值的指针*pstart向前移动,直到找到满足目标值的两数为止;
1.1.4如果两数之和大于目标值,则指向较大值的指针*pend向左移动,直到找到满足目标值的两数为止。
1.2代码如下
1.2.1双指针解法(4ms,9.7MB)
#include <iostream>
#include <vector>
#include <map>
#include <iterator>
using namespace std;
//从一个数组中任意取出两个数,这两个数之和为target
vector<int> twoSum(vector<int>& numbers, int target)
{
vector<int> result(2,-1);
int left = 0, right = numbers.size()-1;
while (left < right)
{
if (numbers[left] + numbers[right] > target)
--right;
else if (numbers[left] + numbers[right] < target)
++left;
else if(numbers[left] + numbers[right] == target)
{
result[0] = left + 1;
result[1] = right + 1;
break;
}
}
return result;
}
int main()
{
vector<int> result, numbers = { 5,6,7,8,9,10 };
int target = 15;
result = twoSum(numbers, target);
for (auto iter = result.begin(); iter != result.end(); iter++)
cout << *iter << endl;
system("pause");
return 0;
}
1.2.2哈希表解法(12ms,10.1MB)
#include <iostream>
#include <vector>
#include <map>
#include <iterator>
using namespace std;
//从一个数组中任意取出两个数,这两个数之和为target
vector<int> twoSum(vector<int>& numbers, int target)
{
vector<int> result;
map<int, int> hashMap;
for (int i = 0; i < numbers.size(); ++i)
{
hashMap.insert(pair<int, int>(numbers.at(i), i));
}
for (int i = 0; i < numbers.size(); ++i)
{
auto iter = hashMap.find(target - numbers.at(i));
if (iter != hashMap.end() && iter->second != i)
{
if (iter->second > i)
{
result.push_back(i + 1);
result.push_back(iter->second + 1);
}
else
{
result.push_back(iter->second + 1);
result.push_back(i + 1);
}
break;
}
}
return result;
}
int main()
{
vector<int> result, numbers = { 5,6,7,8,9,10 };
int target = 11;
result = twoSum(numbers, target);
for (auto iter = result.begin(); iter != result.end(); iter++)
cout << *iter << endl;
system("pause");
return 0;
}
参考内容:
https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/solution/liang-shu-zhi-he-ii-shu-ru-you-xu-shu-zu-by-leetco/(参考:两数之和二:输入有序数组)
来源:CSDN
作者:三公子Tjq
链接:https://blog.csdn.net/naibozhuan3744/article/details/104166061