#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
分析:在给定升序的数组中,返回两个相加和等于指定值得下标,下标都是从1开始的,第一个下标
小于第二个下标。不能使用同一个元素两次。如果找不到,返回两个0
输入:
4(数组元素个数) 9
2 7 11 15
4 5
2 7 11 15
1 1
1
输出:
1 2
0 0
0 0
*/
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> result;
if(numbers.empty() || 1 == numbers.size() )
{
result.push_back(0);
result.push_back(0);
return result;
}
int low = 0;
int high = numbers.size() - 1;
while(low < high)
{
if(numbers.at(low) + numbers.at(high) < target)
{
low++;
}
else if(numbers.at(low) + numbers.at(high) > target)
{
high--;
}
else
{
result.push_back(low+1);
result.push_back(high+1);
return result;
}
}
result.push_back(0);
result.push_back(0);
return result;
}
};
void print(vector<int>& result)
{
if(result.empty())
{
cout << "no result" << endl;
return;
}
int size = result.size();
for(int i = 0 ; i < size ; i++)
{
cout << result.at(i) << " " ;
}
cout << endl;
}
void process()
{
vector<int> nums;
int value;
int num;
Solution solution;
vector<int> result;
int target;
while(cin >> num >> target)
{
nums.clear();
for(int i = 0 ; i < num ; i++)
{
cin >> value;
nums.push_back(value);
}
result = solution.twoSum(nums , target);
print(result);
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:167. Two Sum II - Input array is sorted
最新推荐文章于 2022-05-28 14:42:15 发布