原題:
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;
}
};