原题如下:
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
一、如果给出的数组是有序的,如{2,7,11,15}这种,但是按照有序的做法来做,返回是runtime error,很明显,题目要求是输入无序的数组。下面先把有序数据前提下的解法贴出:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
int endPoints = numbers.size(),beginPoints = 0;
int beginNum,endNum;
beginNum = numbers.at(beginPoints);
endNum = numbers.at(endPoints);
if(beginNum+endNum < target){
return result;
}
while(beginNum<=endNum){
if(beginNum + endNum >target){
endNum = numbers.at(--endPoints);
continue;
}else if(beginNum + endNum <target){
beginNum = numbers.at(++beginPoints);
continue;
}else if(beginNum + endNum ==target){
result.push_back(beginNum);
result.push_back(endNum);
return result;
}
}
return result;
}
};
2、如果是无序的,则代码为:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int endPoints = numbers.size(),beginPoints = 0;
int beginNum,endNum;
vector<int> result;
for(vector<int>::size_type ix = 0;ix != numbers.size();++ix){
for(vector<int>::size_type jx = ix + 1;jx != numbers.size();++jx){
if(numbers.at(ix) + numbers.at(jx) == target){
beginNum = ix;
endNum = jx;
result.push_back(beginNum+1);
result.push_back(endNum+1);
numbers = result;
return numbers;
}
}
}
return result;
}
};