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.(A[Head]+A[End])==target,那么A[Head]和A[End]就是能够满足条件的两个元素,判断结束。2.(A[Head]+A[End])>target, A[End]就不可能是满足条件的元素,因此,End = End - 1,继续进行判断;3.(A[Head]+A[End])<target, A[Head]就不可能是满足条件的元素,因此,Head = Head + 1,继续进行判断;
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { // copy the numbers vector<int> TmpNumbers(numbers); // sort the tmp number vector sort(TmpNumbers.begin(), TmpNumbers.end()); int Size = TmpNumbers.size(); int HeadIndex = 0; int EndIndex = Size - 1; int Start = 0; int End = 0; int SumOfTwo = 0; while(HeadIndex < EndIndex) { Start = TmpNumbers[HeadIndex]; End = TmpNumbers[EndIndex]; SumOfTwo = Start + End; if (SumOfTwo == target) { break; } if (SumOfTwo > target) { EndIndex--; } if (SumOfTwo < target) { HeadIndex++; } } // find the element vector<int>::iterator Ite_1 = find(numbers.begin(), numbers.end(), Start); (*Ite_1) = End - 1; vector<int>::iterator Ite_2 = find(numbers.begin(), numbers.end(), End); // get the index of the element int Index_1 = Ite_1 - numbers.begin() + 1; int Index_2 = Ite_2 - numbers.begin() + 1; if (Index_1 > Index_2) { int Tmp = Index_1; Index_1 = Index_2; Index_2 = Tmp; } vector<int> Result; Result.push_back(Index_1); Result.push_back(Index_2); return Result; } };
原文地址:http://blog.csdn.net/sheng_ai/article/details/44211687