Two Sum(两者之和)
【难度:Easy】
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给定一整数数组,返回其中两个数相加之和为目标值的下标,假设有且只有1个解。
解题思路
最直接的方法是通过两趟循环来遍历所有可能性,来找到符合要求的下标。但是这种方法虽然能过,耗时却比较大。因此可以考虑使用哈希的方法,将整数与其下标绑定,利用map的性质,达到一趟循环解决的目的。
c++代码如下:
简单方法:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
if (nums.empty())
return ans;
for (int i = 0; i < nums.size(); i++) {
ans.push_back(i);
for (int j = i+1; j < nums.size(); j++) {
if (nums[i]+nums[j] == target) {
ans.push_back(j);
return ans;
}
}
ans.pop_back();
}
return ans;
}
};
使用map:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
if (nums.empty())
return ans;
map<int,int> m;
for (int i = 0; i < nums.size(); i++) {
if (m.find(target-nums[i]) != m.end()) {
ans.push_back(m[target-nums[i]]);
ans.push_back(i);
return ans;
}
m[nums[i]] = i;
}
return ans;
}
};