LeetCode OJ(1) —Two Sum
题目描述
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should 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 would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
code(c++)
法一:
vector<int> twoSum(vector<int>& nums, int target) {
int smallIndex;
int residual;
vector<int> ans;
for(int i = 0; i < nums.size(); ++i){
smallIndex = i;
residual = target - nums[i];
for(int j = i+1; j < nums.size(); ++j){
if(nums[j] == residual){
ans.push_back(smallIndex+1);
ans.push_back(j+1);
return ans;
}
}
}
}
法二:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> indMapVal;
vector<int> indices;
for(int i = 0; i < nums.size(); ++i)
indMapVal[nums[i]] = i;
for(int i = 0; i < nums.size(); ++i){
if(indMapVal.find(target - nums[i]) !=
indMapVal.end() &&
indMapVal.find(target - nums[i])->second != i){
indices.push_back(i);
indices.push_back(
indMapVal.find(target - nums[i])->second);
break;
}
}
return indices;
}
注意点
- 这里并没有说容器中每个数都为正数
语法
- 在c++中,定义vector的方式有如下几种:
如果要定义指针类型,则需要new一下,如下所示:
vector *a = new vector();