题目:
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.
解答:
直接用hash即可,在C++中就是map
一开始看错了,看成找这两个数了,如果是这样就直接排序,
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
int size = nums.size();
int left;
for (int i = 0; i < size; ++i)
{
left = target - nums[i];
auto itr = m.find(left);
if (itr != m.end())
return{ i, itr->second };
m[nums[i]] = i;
}
}
};