当前位置:网站首页>Leetcode hot topic Hot 100 - > 1. Sum of two numbers
Leetcode hot topic Hot 100 - > 1. Sum of two numbers
2022-07-28 02:17:00 【Xiao Hao, who wants to enter Dachang】
Description of the stem :
Given an array of integers nums And an integer target value target, Please find... In the array and For the target target the Two Integers , And return their The array subscript .
You can assume Each input will only correspond to one answer . however , Array The same element cannot be repeated in the answer .
You can press In any order Return to the answer .
LeetCode Original link
https://leetcode.cn/problems/two-sum/
Catalog
Method 1: Violence enumeration
Method 1: Violence enumeration
Method 1 analysis :
Just pay attention to The second cycle From the Next position Start traversing , Because Avoid repeating the same subscript .
The code is as follows :
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++) // Because the same element cannot be repeated , So from i+1 Start
{
if (nums[i] + nums[j] == target)
{
ans[0] = i;
ans[1] = j;
}
}
}
return ans;
}
};Complexity analysis :
Time complexity :O(
), among
Is the number of elements in the array , In the worst case, any two numbers in the array must be matched once .
Spatial complexity :O(
), Only constant spaces are opened .
Method 2: Sequencing
Method 2 analysis :
Because it is to find the sum of two numbers , So it's easy to think of Sort After use Double pointer To find , The problem is that the topic requires Returns the subscript , If you sort the original array directly , Then the original subscript cannot be found , So we choose to open up a new Temporary array , And then New array in lookup , After finding two evaluated values , Again Search the original array for subscripts . There is also a problem , Namely Original array There may be Elements of repetition The situation of , So two subscripts must be one Search from front to back , the other one Search back and forth , This avoids finding the same subscript .
The code is as follows :
class Solution {
public:
int FindPosFront(vector<int>& v, int val) // Look back before
{
for (int i = 0; i < v.size(); i++)
{
if (v[i] == val)
{
return i;
}
}
return -1;
}
int FindPosBack(vector<int>& v, int val) // Look backwards
{
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;
}
};Complexity analysis :
Time complexity :O(
), among
Is the number of elements in the array , The time complexity of quicksort is zero O(
), The complexity of other cycle times is O(
), Therefore, take the time complexity of quick sorting .
Spatial complexity :O(
), Opened up a N A temporary array of sizes .
Method 3: Hashtable
Method 3 analysis :
We found that the reason for the high time complexity of method 1 is to find target - x The time complexity of is too high . therefore , It's easy for us to think of establishing Hash map , In this way, you can find target - x The time complexity is reduced to O(N) Down to O(1).
So we create a hash table , For each of these x, Let's first query the hash table Whether there is target - x, then take x Insert into hash table , Subsequent traversal to target-x when , Can then As previously inserted x Pairing , In this way Promise not to let x Match yourself .
The code is as follows :
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]); // Find out whether the corresponding element is in the hash table
if (it != hashtable.end()) // The corresponding element directly returns the result in the hash table
{
ans[0] = it->second;
ans[1] = i;
}
else // If not, add this element , Wait until the loop traverses the corresponding element , You can find this element
{
hashtable[nums[i]] = i;
}
}
return ans;
}
};Complexity analysis :
Time complexity :O(
), among
Is the number of elements in the array . Only traversed the array once .
Spatial complexity :O(
), among
Is the number of elements in the array , Opened up a O(
) Size hash table .
That's all for sharing , I'm not very talented , There must be mistakes or thoughtlessness , If there are corrections or suggestions , Welcome to leave a message in the comment area , I will reply immediately after seeing it and make appropriate changes to the article after thinking , Thank you for reading ~
边栏推荐
猜你喜欢

IT这个岗位,人才缺口百万,薪资水涨船高,上不封顶

11-Django-基础篇-数据库操作

云原生爱好者周刊:Prometheus 架构演进之路

如何评估研发人员效能?软件工程师报告帮你看见每个人的贡献

借助Elephant&nbsp;Swap打造的ePLATO,背后的高溢价解析

CeresDAO:全球首个基于DAO赋能Web3.0的去中心化数字资产管理协议

Record a production deadlock

Huawei app UI automation test post interview real questions, real interview experience.

都在说DevOps,你真正了解它吗?

Two ways for wechat applet to realize dynamic horizontal step bar
随机推荐
LeetCode 热题 HOT 100 -> 2.两数相加
Wechat applet pictures are scaled according to the screen scale
mongodb/mongoTemplate.upsert批量插入更新数据的实现
Principle and implementation of focal loss
每条你收藏的资讯背后,都离不开TA
MySQL的pymysql操作
Talk to ye Yanxiu, an atlassian certification expert: where should Chinese users go when atlassian products enter the post server era?
uniapp 总结篇 (小程序)
一文读懂Plato&nbsp;Farm的ePLATO,以及其高溢价缘由
Uniapp summary (applet)
54:第五章:开发admin管理服务:7:人脸入库流程;人脸登录流程;浏览器开启视频调试模式(以便能够在本机的不安全域名的情况下,也能去开启摄像头);
这个操作可能不值钱,但却值得学习 | 【图片批量裁剪】
软考 --- 数据库(2)关系模型
Data output - image annotation and annotation
[深入研究4G/5G/6G专题-42]: URLLC-14-《3GPP URLLC相关协议、规范、技术原理深度解读》-8-低延时技术-2-基于slot的调度与Slot内灵活的上下行符号配比
CeresDAO:Ventures DAO的“新代言”
Execute add migration migration and report build failed
LeetCode 热题 HOT 100 -> 3. 无重复字符的最长子串
你所不知道的WMS
Two ways for wechat applet to realize dynamic horizontal step bar
https://leetcode.cn/problems/two-sum/