1. Two Sum【easy】

1. 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, 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].

解法一:

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> u_map;
vector<int> result; for (int i = ; i < nums.size(); ++i)
{
if (u_map.find(target - nums[i]) != u_map.end())
{
result.push_back(u_map[target - nums[i]]);
result.push_back(i);
return result;
} u_map.insert(make_pair(nums[i], i));
} return result;
}
};

map搞一把

解法二:

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
int n = (int)nums.size();
for (int i = ; i < n; i++) {
auto p = map.find(target - nums[i]);
if (p != map.end()) {
return {p->second, i};
}
map[nums[i]] = i;
}
}
};

比较简洁的写法

扩展见:

167. Two Sum II - Input array is sorted【easy】

170. Two Sum III - Data structure design【easy】

上一篇:二模13day1解题报告


下一篇:NOIP2016提高组解题报告