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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]
大意为,给定一个数组,和一个目标值,要求从数组中选出两个数字之和等于目标值,返回两个值在数组中的下标。
class Solution {
public:
int sum;
vector<int> twoSum(vector<int>& nums, int target) {
int sum = target;
vector<int> out;
int a, b;
for (int i = 0; i < nums.size();i++ ) {
target = sum;
target-=nums[i];
a = i;
for (int j = i+1; j < nums.size(); j++) {
if(target == nums[j]) {
b = j;
out.push_back(a);
out.push_back(b);
return out;
}
}
}
return out;
}
};
暴力求解,速度是C++提交中的50%。