原题:
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].
C++实现:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i,j,s=nums.size();
vector<int> result(2,-1);
for(i=0;i<s-1;i++){
for(j=i+1;j<s;j++){
if(nums[i]+nums[j]==target){
result[0]=i;
result[1]=j;
return result;
}
}
}
return result;
}
};