1. Two Sum
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].
方法:使用一个map,该map以原数组中的值为键,下标为值。扫描数组nums中第i个元素时,查看target-nums[i]是否在map中,若在则可得到结果。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
map<int, int> dic;
for (int i = 0; i < nums.size(); i++)
{
if (dic.find(target-nums[i]) != dic.end())
{
result.push_back(dic[target - nums[i]]);
result.push_back(i);
return result;
}
else
{
dic[nums[i]] = i;
}
}
return result;
}
};
还没有评论,来说两句吧...