Problem:Given an array of integers, find two numbers such that they add up to a specific target number.
The function twosum shocould 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 wowould have exactly one solution.
Input:Numbers = {2, 7, 11, 15}, target = 9
Output:Index1 = 1, index2 = 2
Due to the level problem, this question refers to the idea of suool. Because I first thought of two for statements, the first for statement, and the second for statement, the first for statement, and the first for statement, the first for statement, and the first for statement.
class resolution{public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int>::iterator iter, res; vector<int> result(2); res = result.begin(); for (iter = numbers.begin();iter != numbers.end();++iter) { for (vector<int>::iterator iter2 = iter + 1;iter2!=numbers.end();++iter2) { if(*iter + *iter2 == target) { *res = iter - numbers.begin() + 1; *(++res) = iter2 - numbers.begin() + 1; return result; } } } }};
As you can imagine, the running times out, so after calmly referring to suool, I thought about this as the lowest N-party complexity. Since it times out, it should be solved by nlogn. Consider sorting nlogn. Then sort it. Use STD: sort.
After sorting, you can use the sum of the beginning and end to judge and keep indent until you find the answer.
If the sum of the header and tail is smaller than the target value, the first step can be increased.
If the sum of the header and tail is greater than the target value, the end must be reduced.
Because there is only one answer, you can find the answer by indentation.
After finding the answer, find the key value in the original vector, and traverse 2N to find the subscript, push_back to the result.
class Solution{public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; vector<int> temp = numbers; std::sort(temp.begin(),temp.end()); int left = 0; int right = temp.size() - 1; int sum = 0; int index = 0; while(left < right) { sum = temp[left] + temp[right]; if (sum == target) { while(true) { if(numbers[index] == temp[left]) { result.push_back(index + 1); } // must be ‘else if‘ or the same index will be push_back when the target is composed by two same numbers else if(numbers[index] == temp[right]) { result.push_back(index + 1); } if(result.size() == 2) { return result; } index++; } } else if (sum < target) { left++; } else { right--; } } }};
That's all. Note that when else if is in use, the case where the same value is added to the target will cause the index of the error log. You can change else if to submit and check the error message.
There is a more embarrassing God actually used n to solve the http://www.tuicool.com/articles/RBNjuu
Leetcode -- two sum