当前位置:网站首页>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 ~
边栏推荐
- 【网站搭建】使用acme.sh更新ssl证书:将zerossl改为letsencrypt
- 小程序毕设作品之微信校园浴室预约小程序毕业设计成品(1)开发概要
- Which database is the fastest to query data only?
- [机缘参悟-53]:阳谋立身,阴谋防身
- Structure pseudo class selector - find single - find multiple - nth of type and pseudo elements
- 【愚公系列】2022年07月 Tabby集成终端的使用
- 都在说DevOps,你真正了解它吗?
- go 学习01
- Appium 点击操作梳理
- Under the new retail format, retail e-commerce RPA helps reshape growth
猜你喜欢

synchronized详解

In it, there is a million talent gap, and the salary rises, but it is not capped

The cooperation between starfish OS and metabell is just the beginning

Clear the cause of floating and six methods (solve the problem that floating affects the parent element and the global)

Synchronized details

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

这个操作可能不值钱,但却值得学习 | 【图片批量裁剪】
![[database data recovery] data recovery case of insufficient disk space of SQL Server database](/img/0e/908db40e1e8b7dd62e12558c1c6dc4.png)
[database data recovery] data recovery case of insufficient disk space of SQL Server database

了解加密行业的“下一个大趋势”——Ventures DAO

考研数学一元微分学证明题常见题型方法
随机推荐
Unittest单元测试框架全栈知识
轻量版项目管理系统
54:第五章:开发admin管理服务:7:人脸入库流程;人脸登录流程;浏览器开启视频调试模式(以便能够在本机的不安全域名的情况下,也能去开启摄像头);
Xiaomi website homepage big module - small module + navigation (floating case)
Flume (5 demos easy to get started)
MySQL的pymysql操作
IT这个岗位,人才缺口百万,薪资水涨船高,上不封顶
新零售业态下,零售电商RPA助力重塑增长
软件测试面试题:你认为做好测试用例设计工作的关键是什么?
Common problem types and methods of mathematical univariate differential proof problems in postgraduate entrance examination
Zkrollup learning materials summary
Wechat applet pictures are scaled according to the screen scale
【数据库数据恢复】SQL Server数据库磁盘空间不足的数据恢复案例
组原必备知识点
Principle and implementation of focal loss
一种比读写锁更快的锁,还不赶紧认识一下
二叉树的遍历和性质
测试/开发程序员的级别“陷阱“,级别不是衡量单维度的能力......
Software testing interview question: what is the purpose of test planning? What are the contents of the test plan? Which are the most important?
交叉熵原理及实现
https://leetcode.cn/problems/two-sum/