Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
使用时间复杂度为O(n^2)的算法:
class Solution{
public:
vector<int> twoSum(vector<int> & nums, int target){
vector<int> answer = { 0, 0 };
for (unsigned int i = 0; i < nums.size(); ++i){
answer[0] = i;
int b = target - nums[i];
for (unsigned int j = i + 1; j < nums.size(); ++j){
if (nums[j] == b){
answer[1] = j;
break;
}
}
if (0 != answer[1])
break;
}
cout << answer[0] << "," << answer[1] << endl;
return answer;
}
};