当前位置:网站首页>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 ~
边栏推荐
- MySQL的pymysql操作
- The cooperation between starfish OS and metabell is just the beginning
- Product interpretation - Design and distributed expansion of metersphere UI test module
- 【愚公系列】2022年07月 Go教学课程 019-循环结构之for
- 一文读懂Plato&nbsp;Farm的ePLATO,以及其高溢价缘由
- Principle and implementation of cross entropy
- Codeworks round 807 (Div. 2) a-c problem solution
- 了解加密行业的“下一个大趋势”——Ventures DAO
- Appium click operation sorting
- Under the new retail format, retail e-commerce RPA helps reshape growth
猜你喜欢

重要安排-DX12引擎开发课程后续直播将在B站进行

微信小程序实现动态横向步骤条的两种方式
![53: Chapter 5: develop admin management service: 6: develop [admin administrator exit login, interface]; (one point: when we want to modify a value with a certain coding method, the new value should b](/img/9a/674308c7a21fa2be0943ca7967e274.png)
53: Chapter 5: develop admin management service: 6: develop [admin administrator exit login, interface]; (one point: when we want to modify a value with a certain coding method, the new value should b

UE4 unreal ndisplay plug-in easy to use three fold screen details

Vxe Table/Grid 单元格分组合并

Flex开发网页实例web端

二叉树的遍历和性质

Codeworks round 810 (Div. 2) a~c problem solution
![[机缘参悟-53]:阳谋立身,阴谋防身](/img/93/2f61993770d93d9adc80a9fa89e71c.jpg)
[机缘参悟-53]:阳谋立身,阴谋防身

学会这招再也不怕手误让代码崩掉
随机推荐
Synchronized details
A letter to the user of qubu drawing bed
Flex布局学习完成PC端
UE4 unreal ndisplay plug-in easy to use three fold screen details
focal loss原理及实现
CeresDAO:全球首个基于DAO赋能Web3.0的去中心化数字资产管理协议
执行 Add-Migration 迁移时报 Build failed.
Record a production deadlock
Xiaomi website homepage big module - small module + navigation (floating case)
mysql创建存储过程---------[HY000][1418] This function has none of DETERMINISTIC, NO SQL
借助Elephant&nbsp;Swap打造的ePLATO,背后的高溢价解析
云原生爱好者周刊:Prometheus 架构演进之路
53:第五章:开发admin管理服务:6:开发【admin管理员退出登录,接口】;(一个点:我们想要修改一个采用了某种编码方式的值时,新的值最好也按照这种编码方式编码后,再去修改;)
Software testing interview question: what do you think is the key to good test case design?
清除浮动的原因和六种方法(解决浮动飞起影响父元素和全局的问题)
考研数学一元微分学证明题常见题型方法
Typescript中类的使用
这个操作可能不值钱,但却值得学习 | 【图片批量裁剪】
Software testing interview question: what types of software testing are you familiar with?
微信小程序图片根据屏幕比例缩放