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++ solution:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int size = nums.size();
int temp;
vector<int> res;
int flag = 0;
for(int i = 0; i < size; i++) {
temp = target - nums[i];
for(int j = i+1; j < size; j++) {
if(temp == nums[j]) {
res.push_back(i);
res.push_back(j);
flag = 1;
break;
}
}
if(flag == 1) {
break;
}
}
return res;
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> a;
vector<int> result;
for (int i = 0; i < nums.size(); i++) {
a[nums[i]] = i;
}
for (int i = 0; i < nums.size(); i++) {
int t = target - nums[i];
if (a.count(t) && a[t] != i) {
result.push_back(i);
result.push_back(a[t]);
break;
}
}
return result;
}
};
题目给出一组数组和一个目标,要求在数组中找到两个不同元素的和等于该目标,理解为:nums[a]+nums[b]=target,结果返回数组下标a,b。当选定nums[a],可知nums[b]=target-nums[a],只需查找数组中是否含有该数值。通过unordered_map确认nums[b]和 i 值。
当搜索涉及到下标时,一种参考处理。一般的数组是以下标为索引,查找对应值,转化为,将对应值作为索引,查找下标。array、vector、map的使用有其共通之处。