当前位置:网站首页>LeetCode1_ Sum of two numbers
LeetCode1_ Sum of two numbers
2022-07-07 15:42:00 【WhiteTian】
Original article , Reprint please indicate the source .
Topic type : Simple type
C++ Explain Sum of two numbers
The title is as follows
Given an array of integers nums And an integer target value target, Please find... In the array And is the target value target the Two Integers , And return their array subscripts .
You can assume that each input corresponds to only one answer . however , The same element in the array cannot be repeated in the answer .
You can return the answers in any order .
Example 1:
Input :nums = [2,7,11,15], target = 9
Output :[0,1]
explain : because nums[0] + nums[1] == 9 , return [0, 1] .
Example 2:
Input :nums = [3,2,4], target = 6
Output :[1,2]
Example 3:
Input :nums = [3,3], target = 6
Output :[0,1]
Tips :
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
There will only be one valid answer
Advanced : You can come up with a time complexity less than O(n2) The algorithm of ?
solution 1
The first is the easiest to think of , Ideas : Two layers of for loop , Enumerate all the situations , Find subscript .
But the time complexity is O(n^2), Spatial complexity O(1)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size() - 1; i++)
{
for (int j = i + 1; j < nums.size(); j++)
{
if (nums[i] + nums[j] == target)
{
return {
i, j };
}
}
}
return {
};
}
};
See the above Time complexity O(n^2), n= The length of the array , The space complexity is O(1)
leetcode Execution score of 
Then I thought of trading space for time , So there is a second solution
solution 2
Ideas : Use one map/unordered_map, here unordered_map be better than map, Then it will traverse once vector, In the process of traversal, each value is 8 reduce ,
Then judge what is after subtraction , Then take the number after subtraction map Of key Inside looking for .
If you find , So we found , The first subscript is map This key Corresponding value(key save vector Value ,value Save subscript );
On the contrary, if it is not found , take vector[i] Add to map Of key On ,value yes i.
map Achieved Red and black trees
Time complex reading O(logn), because map Lookup 、 Delete 、 Increase the time complexity of a series of operations such as stable , All for logn
Complex reading space O(n)
unordered_map Achieved Hashtable
Time complex reading O(c-n), lookup 、 Delete 、 It's fast to add , The time complexity is constant O
Complex reading space O(n)
because unordered_map Internally based on hash table , With (key,value) Store in the form of pairs , So the occupancy rate is high Unordered_map Lookup 、 Delete 、 The added time complexity is unstable , Average is O, Depending on the hash function . In extreme cases it could be O(n)
Look at the diagram 
Code implementation map Of
class Solution {
public:
// The second solution .key=value value=index
vector<int> twoSum(vector<int>& nums, int target) {
std::map<int, int> contentmap;
for (int i = 0; i < nums.size(); i++)
{
int less = target - nums[i];
map<int, int>::iterator iter;
iter = contentmap.find(less);
if (iter != contentmap.end())
{
return {
contentmap[less], i };
}
else
{
contentmap[nums[i]] = i;//.insert(pair(nums[i], i));
}
}
return {
};
}
};
Code implementation unordered_map Of , This solution is better than that based on map Solution
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 {
};
}
};
leetcode Execution score of 
I hope I can work out a better solution
thank you , It's not easy to create , Great Xia, please stay … Move your lovely hands , Give me a compliment before you go <( ̄︶ ̄)>
边栏推荐
- The rebound problem of using Scrollview in cocos Creator
- 【数字IC验证快速入门】29、SystemVerilog项目实践之AHB-SRAMC(9)(AHB-SRAMC SVTB Overview)
- leetcode 241. Different Ways to Add Parentheses 为运算表达式设计优先级(中等)
- 【数字IC验证快速入门】26、SystemVerilog项目实践之AHB-SRAMC(6)(APB协议基本要点)
- 【深度学习】图像超分实验:SRCNN/FSRCNN
- Getting started with webgl (4)
- HW primary flow monitoring, what should we do
- Do not use memset to clear floating-point numbers
- Webgl texture
- 【数字IC验证快速入门】22、SystemVerilog项目实践之AHB-SRAMC(2)(AMBA总线介绍)
猜你喜欢

Use cpolar to build a business website (2)

Gd32 F3 pin mapping problem SW interface cannot be burned
![[quick start of Digital IC Verification] 20. Basic grammar of SystemVerilog learning 7 (coverage driven... Including practical exercises)](/img/d3/cab8a1cba3c8d8107ce4a95f328d36.png)
[quick start of Digital IC Verification] 20. Basic grammar of SystemVerilog learning 7 (coverage driven... Including practical exercises)

#HPDC智能基座人才发展峰会随笔
![[Data Mining] Visual Pattern Mining: Hog Feature + cosinus Similarity / K - means Clustering](/img/a4/7320f5d266308f6003cc27964e49f3.png)
[Data Mining] Visual Pattern Mining: Hog Feature + cosinus Similarity / K - means Clustering

Unity之ASE实现卡通火焰

有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?

Super simple and fully automated generation super signature system (cloud Xiaoduo minclouds.com cloud service instance), free application in-house test app distribution and hosting platform, maintenan

【数字IC验证快速入门】24、SystemVerilog项目实践之AHB-SRAMC(4)(AHB继续深入)

Actually changed from 408 to self proposition! 211 North China Electric Power University (Beijing)
随机推荐
Tkinter after how to refresh data and cancel refreshing
【数据挖掘】视觉模式挖掘:Hog特征+余弦相似度/k-means聚类
[server data recovery] data recovery case of raid failure of a Dell server
OpenGL's distinction and understanding of VAO, VBO and EBO
Ctfshow, information collection: web13
Cocos makes Scrollview to realize the effect of zooming in the middle and zooming out on both sides
[quick start of Digital IC Verification] 18. Basic grammar of SystemVerilog learning 5 (concurrent threads... Including practical exercises)
Stm32f103c8t6 PWM drive steering gear (sg90)
Do not use memset to clear floating-point numbers
Getting started with webgl (1)
避坑:Sql中 in 和not in中有null值的情况说明
TypeScript 发布 4.8 beta 版本
Vertex shader to slice shader procedure, varying variable
Getting started with webgl (3)
[quick start of Digital IC Verification] 26. Ahb-sramc of SystemVerilog project practice (6) (basic points of APB protocol)
2. Basic knowledge of golang
The bank needs to build the middle office capability of the intelligent customer service module to drive the upgrade of the whole scene intelligent customer service
2022年5月互联网医疗领域月度观察
【數字IC驗證快速入門】26、SystemVerilog項目實踐之AHB-SRAMC(6)(APB協議基本要點)
leetcode 241. Different ways to add parentheses design priority for operational expressions (medium)