题目
给定一个整数数组nums和目标值target,请再数值中找出和为目标值得两个整数,并返回下标值。你可以假设每个输入只对应一种答案,但不能利用这个数组中重复得元素。
解题思路
1. 暴力枚举
思路及算法:
枚举数组中的每一个整数x,在剩余的数组中寻找target-x;需要注意的是,数组中的每一个变量只枚举一次,因此在遍历时,只需要遍历x之后的整数即可;
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return { i, j };
}
}
}
return {};
}
};
int main()
{
vector<int> nums{ 2, 7, 11, 15 };
int target = 14;
Solution m_solution;
vector<int> index = m_solution.twoSum(nums, target);
}
- 时间复杂度:O(N2)
- 空间复杂度:O(1)
2. 哈希表
思路及算法:
首先创建一个哈希表,对于数组中的每一个x,可以现在哈希表中查询是否催在target-x,若存在,则直接返回数组与索引,若不存在,则将当前数组存储为键值key,其对应索引存储为值value。
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return { i, j };
}
}
}
return {};
}
vector<int> twoSum2(vector<int>& nums, int target) {
unordered_map<int, int> hashtable; //创建一个无序哈希表
int n = nums.size();
for (int i = 0; i < n; ++i) {
auto it = hashtable.find(target - nums[i]); //查找是否存在target-nums[i]
if (it != hashtable.end()) {
return { it->second, i }; //存在则范围搜索到的键值对应的value,与当前数组的索引
}
hashtable[nums[i]] = i; //若未搜索到,则存入当前整数数组及其索引
}
return {};
}
};
int main()
{
vector<int> nums{ 2, 7, 11, 15 };
int target = 9;
Solution m_solution;
vector<int> index = m_solution.twoSum2(nums, target);
}
- 时间复杂度:O(N)
- 空间复杂度:O(N)