题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
暴力解法
vector<int> twoSum(vector<int>& v, int target) {
size_t size = nums.size();
vector<int> res(2, 0);
for(int i = 0; i < size; ++i)
{
for(int j = i + 1; j < size; ++j)
{
if(v[i] + v[j] == target)
{
res[0] = i;
res[1] = j;
break;
}
}
}
return res;
}
执行用时 :184 ms, 在所有 C++ 提交中击败了41.23%的用户
内存消耗 :11.3 MB, 在所有 C++ 提交中击败了5.14%的用户
用hashmap查找
vector<int> twoSum(vector<int>& v, int target) {
size_t size = nums.size();
vector<int> res(2, 0);
unordered_map<int ,int> m;
for(int i = 0; i < size; ++i)
m.insert(make_pair(v[i], i));
for(int i = 0; i < size; ++i)
{
auto itFind = m.find(target - v[i]);
if(itFind == m.end() || itFind->second == i)
continue;
res[0] = i;
res[1] = itFind->second;
break;
}
return res;
}
执行用时 :8 ms, 在所有 C++ 提交中击败了96.91%的用户
内存消耗 :12.6 MB, 在所有 C++ 提交中击败了5.14%的用户