当前位置:网站首页>LeetCode 热题 HOT 100 -> 1.两数之和
LeetCode 热题 HOT 100 -> 1.两数之和
2022-07-28 00:49:00 【想进大厂的小皓同学】
题干描述:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和 为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
目录
方法1:暴力枚举
方法1分析:
只要注意第二层循环要从该元素的下一个位置开始遍历即可,因为要避免同一个下标重复出现。
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>ans(2);
for (int i = 0; i < nums.size(); i++)
{
for (int j = i + 1; j < nums.size(); j++) //由于同一个元素不能重复出现,因此从i+1开始
{
if (nums[i] + nums[j] == target)
{
ans[0] = i;
ans[1] = j;
}
}
}
return ans;
}
};复杂度分析:
时间复杂度:O(
),其中
是数组中的元素个数,最坏情况下数组中任意两个数都要被匹配一次。
空间复杂度:O(
),仅开了常数个空间。
方法2:排序法
方法2分析:
因为是要查找两个数的和,所以很容易想到排序后使用双指针的方法来查找,问题在于题目要求返回下标,如果直接对原数组进行排序,那么就无法找到原下标了,因此我们选择开辟一个新的临时数组,再在新数组中查找,找到两个所求值之后,再在原数组中搜索下标。这里面还存在一个问题,就是原数组可能存在有重复的元素的情况,因此两个下标必须一个从前往后查找,另一个从后往前查找,这样就能避免找到同一个下标。
代码如下:
class Solution {
public:
int FindPosFront(vector<int>& v, int val) //从前往后找
{
for (int i = 0; i < v.size(); i++)
{
if (v[i] == val)
{
return i;
}
}
return -1;
}
int FindPosBack(vector<int>& v, int val) //从后往前找
{
for (int i = v.size() - 1; i >= 0; i--)
{
if (v[i] == val)
{
return i;
}
}
return -1;
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans(2);
vector<int> tmp(nums);
sort(tmp.begin(), tmp.end());
int begin = 0;
int end = nums.size() - 1;
while (begin < end)
{
if (tmp[begin] + tmp[end] < target)
{
begin++;
}
else if (tmp[begin] + tmp[end] > target)
{
end--;
}
else
{
ans[0] = FindPosFront(nums, tmp[begin]);
ans[1] = FindPosBack(nums, tmp[end]);
break;
}
}
return ans;
}
};复杂度分析:
时间复杂度:O(
),其中
是数组中的元素个数,快速排序的时间复杂度为O(
),其余循环时间复杂度均为O(
),因此取快速排序的时间复杂度。
空间复杂度:O(
),开辟了一个N个大小的临时数组。
方法3:哈希表
方法3分析:
我们发现方法一的时间复杂度较高的原因是寻找 target - x 的时间复杂度过高。因此,我们很容易想到建立哈希映射,这样便可以将寻找 target - x 的时间复杂度降低到O(N)降低到 O(1)。
这样我们创建一个哈希表,对于每一个 x,我们首先查询哈希表中是否存在 target - x,然后将 x 插入到哈希表中,后续遍历到 target-x 时,便可以与之前插入的 x 进行配对,这样即可保证不会让 x 和自己匹配。
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
vector<int> ans(2);
for (int i = 0; i < nums.size(); ++i)
{
auto it = hashtable.find(target - nums[i]); //查找对应元素在不在哈希表内
if (it != hashtable.end()) //对应元素在哈希表中就直接返回结果
{
ans[0] = it->second;
ans[1] = i;
}
else //不在则添加本元素,等到循环遍历到对应元素时,则可以查找到本元素
{
hashtable[nums[i]] = i;
}
}
return ans;
}
};复杂度分析:
时间复杂度:O(
),其中
是数组中的元素个数。仅对数组遍历了一遍。
空间复杂度:O(
),其中
是数组中的元素个数,开辟了一个O(
)大小的哈希表。
该题的分享就到这里,本人才疏学浅,肯定会有错误或考虑不周到的地方,如有纠错或建议,非常欢迎在评论区留言,我看见后会立刻回复并在思考后对文章作出合适的修改,感谢阅读~
边栏推荐
- HyperMesh circular array - plug in
- Aike AI frontier promotion (7.14)
- [website construction] update SSL certificate with acme.sh: change zerossl to letsencrypt
- MySQL的pymysql操作
- Hcip 13th day notes
- 【愚公系列】2022年07月 Go教学课程 019-循环结构之for
- [database data recovery] data recovery case of insufficient disk space of SQL Server database
- 都在说DevOps,你真正了解它吗?
- Zkrollup learning materials summary
- 记录一次生产死锁
猜你喜欢

Forget the root password

Sample imbalance - entry 0

Skywalking distributed system application performance monitoring tool - medium

JS what situations can't use json Parse, json.stringify deep copy and a better deep copy method

执行 Add-Migration 迁移时报 Build failed.

二叉树的遍历和性质

Go learning 01

Interviewer: are you sure redis is a single threaded process?

Packet capturing wizard netcapture app packet capturing tutorial "complete"

Talk to ye Yanxiu, an atlassian certification expert: where should Chinese users go when atlassian products enter the post server era?
随机推荐
Fiddler mobile packet capturing agent settings (for Huawei glory 60s)
Flex布局学习完成PC端
sftp文件/文件夹上传服务器
Typescript中类的使用
交叉熵原理及实现
Software testing interview question: what do you think is the key to good test case design?
C# 使用Abp仓储访问数据库时报错记录集
Common modules of ros2 launch files
Skywalking distributed system application performance monitoring tool - medium
Flex development web page instance web side
The petrochemical industry is facing the tide of rising prices, and the digital dealer distribution system platform enables dealers and stores
软件测试面试题:请详细介绍一下各种测试类型的含义?
Behind every piece of information you collect, you can't live without TA
Implementation of mongodb/mongotemplate.upsert batch inserting update data
软件测试面试题:常见的 POST 提交数据方式
Codeforces Round #810 (Div. 2)A~C题解
CeresDAO:Ventures DAO的“新代言”
C # using ABP warehouse to access the database error record set
LeetCode 热题 HOT 100 -> 3. 无重复字符的最长子串
Unreal ue4.27 switchboard porting engine process
https://leetcode.cn/problems/two-sum/