LeetCode 1:两数之和
题目
解法1:暴力枚举
在写的时候必须要加入对应的头文件
< vector > 头文件指的是向量类型。
暴力枚举很简单,就是将其都遍历一遍然后寻找结果
这样时间复杂度是n^2,空间开销比较小,只有n
所以是以时间换空间。
#include<vector>
#include <iostream>
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 {};
}
};
解法2:哈希表
一般空间够用,时间不够用
所以可以用二叉树搜索和哈希表
因为不需要维护数据的顺序性,所以使用哈希表。
建立哈希表,先把第一个元素放入
用target减去后面的每一个元素,如果最后的差在哈希表里面
就输出数组下表,不在哈希表内,就将其存入哈希表。
// @before-stub-for-debug-end
/*
* @lc app=leetcode.cn id=1 lang=cpp
*
* [1] 两数之和
*/
// @lc code=start
#include <vector>
#include <iostream>
// 调用哈希表的标准库
#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可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型
// 在哈希表中寻找数值为target-nums[i]的
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end())
// 如果没有到哈希表的尾部
{
return {it->second, i};
// (*it).first; // the key value (of type Key)
// (*it).second; // the mapped value (of type T)
// (*it); // the "element value" (of type pair<const Key,T>)
}
hashtable[nums[i]] = i;
// 将数组下表存入值,将数组的值存入键
}
return {};
}
};
// @lc code=end
本文来自博客园,作者:{Zeker62},转载请注明原文链接:https://www.cnblogs.com/Zeker62/p/15046230.html