力扣简单题两数之和
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- 只会存在一个有效答案
暴力解法
我的题解思路:
遍历nums数组,对于nums数组中的每一个值x,首先用target的值减去x,得到的差值diff与数组中其余的所有数值对比,有相同的则匹配成功,返回两个数值的坐标,算法复杂度为O(n^2)
问题:
编译程序的时候出现警告:
warning: control reaches end of non-void function
这是因为没有确保每个控制流都有返回值,在循环结束的地方加上return语句即可
完整代码:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
for (int i = 0; i < nums.size(); ++i) {
int diff = target - nums[i];
for (int j = i + 1; j < nums.size(); ++j) {
if (diff == nums[j]) {
return vector<int> { i, j };
break;
} //if
} //for j
} //for i
return vector<int> { 0, 0 };
}
};
int main() {
vector<int> nums { 3, 3 };
int target = 6;
Solution s;
vector<**int**> res = s.twoSum(nums, target);
cout << res[0] << "," << res[1] << **endl**;
return 0;
}
优化题解:哈希表
使用哈希表,可以将寻找target-x的时间复杂度降低到从 O(N) 降低到 O(1)。
创建一个哈希表,对于每一个 x
,我们首先查询哈希表中是否存在 target - x
,然后将 x
插入到哈希表中,即可保证不会让 x
和自己匹配。
完整代码:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
unordered_map<int,int> hashtable;
for ( int i = 0; i < nums.size(); ++ i) {
auto it = hashtable.find(target - nums[i]); //寻找在哈希表中是否有对应值
if(it != hashtable.end()){// end( )函数返回一个指向哈希表结尾位置的下一个元素的迭代器
return {it->second,i}; //it->first是输出对应key值,it->second是输出key对应的value值
}
hashtable[nums[i]] = i;
}
return {};
}
};
int main() {
vector<int> nums { 3, 2, 4 };
int target = 6;
Solution s;
vector<int> res = s.twoSum(nums, target);
cout << res[0] << "," << res[1] << endl;
return 0;
}