Leetcode两数之和
-
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
-
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
-
解法
(1) 暴力法:遍历每个元素 xx,并查找是否存在一个值与 target - xtarget−x 相等的目标元素。
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
vector<int> res;
int numsSize = int(nums.size());
for (int index = 0; index < numsSize; index++)
{
int b = target - nums[index];
//注意index2 = index + 1,数字不能重复使用
for (int index2 = index + 1; index2 < numsSize; index2++)
{
if (nums[int(index2)] == b)
{
res.push_back(index);
res.push_back(index2);
return res;
}
}
}
return res;
}
};
(2)利用hashmap
a.两遍哈希表
在第一次迭代中,我们将每个元素的值和它的索引添加到表中。然后,在第二次迭代中,我们将检查每个元素所对应的目标元素(target - nums[i]target−nums[i])是否存在于表中。注意,该目标元素不能是nums[i] 本身!
class Solution { public: vector<int> twoSum(vector<int> &nums, int target) { unordered_map<int, int> hash; vector<int> result; int numsSize = int(nums.size()); for(int i=0; i<numsSize; i++) hash[nums[i]] = i; for(int j=0; j<numsSize; j++){ int ToBeFound = target - nums[j]; // 找到元素,并且两个索引不相等 if(hash.find(ToBeFound) != hash.end() && hash[ToBeFound] != j){ result.push_back(j); result.push_back(hash[ToBeFound]); break; // 跳出循环,因为会出现多个结果 } } return result; } };
b. 一遍哈希表
在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。
class Solution { public: vector<int> twoSum(vector<int> &nums, int target) { unordered_map<int, int> hash; vector<int> result; int numsSize = int(nums.size()); for(int j=0; j<numsSize; j++){ int ToBeFound = target - nums[j]; // 找到元素,并且两个索引不相等 if(hash.find(ToBeFound) != hash.end() && hash[ToBeFound] != j){ result.push_back(hash[ToBeFound]); result.push_back(j); break; } hash[nums[j]] = j; } return result; } };

浙公网安备 33010602011771号