当前位置:网站首页>Leetcode 1-sum of two numbers
Leetcode 1-sum of two numbers
2020-11-10 08:39:00 【open_nfiwhlc1】
List of articles
Title Description
Given an array of integers and a target value , Find the two numbers in the array that are the target values .
You can assume that each input corresponds to only one answer , And the same elements cannot be reused .
Example :
Given nums = [2, 7, 11, 15], target = 9
because nums[0] + nums[1] = 2 + 7 = 9
So back [0, 1]
Method 1
Violence enumeration
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int length=nums.size();
vector<int> result;
for(int i=0;i<length;i++)
{
for(int j=i+1;j<length;j++)
{
if(target==nums[i]+nums[j])
{
result.push_back(i);
result.push_back(j);
break;
}
}
}
return result;
}
};
Ideas and algorithms
The easiest way to think of is to enumerate every number in an array x, Look for the existence of target - x.
When we look for target - x when , It needs to be noted that each is located in x All the previous elements have been associated with x Matched , So there's no need to match again . And each element cannot be used twice , So we just need to x Look for... In the following elements target - x.
Complexity analysis
- Time complexity :O(N^2)O(N2), among NN 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(1)O(1).
Method 2
Hashtable
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};
Ideas and algorithms
Note that the reason for the high time complexity of method 1 is to find target - x The time complexity of is too high . therefore , We need a better approach , Can quickly find whether the target element exists in the array . If there is , We need to find out its index .
Use hash table , You can look for target - x The time complexity is reduced to from O(N)O(N) Down to O(1)O(1).
So we create a hash table , For each of these x, We first query the hash table for the presence of target - x, And then x Insert into hash table , You can guarantee that you won't let x Match yourself .
Complexity analysis
- Time complexity :O(N)O(N), among NN Is the number of elements in the array . For each element x, We can O(1)O(1) Looking for target - x.
- Spatial complexity :O(N)O(N), among NN Is the number of elements in the array . Mainly for the cost of hash table .
版权声明
本文为[open_nfiwhlc1]所创,转载请带上原文链接,感谢
边栏推荐
- csdn bug1:待加
- CSDN bug3: to be added
- 【LeetCode】 92 整数反转
- jmeter接口测试--带有token的解决方法
- iNeuOS工业互联平台,WEB组态(iNeuView)增加工程视图导入、导出功能,及优化和修复,发布:v3.2.1版本
- CUDA_获取指定设备
- [paper reading notes] a multilayered informational random walk for attributed social network embedding
- 假如需要一百万个对象
- Several solutions to the problem that selenium webdriver always fails to use click
- What's the difference between delete, truncate, and drop, and what to do if you delete data by mistake
猜你喜欢
js解决浏览器打印自动分页的问题
csdn bug5:待加
关于centos启动报错:Failed to start Crash recovery kernel arming的解决方案
Several solutions to the problem that selenium webdriver always fails to use click
Use call, apply and bind to solve the annoying this in JS, this in event binding and parameter passing
Difficulties in heterogeneous middleware implementation of Bifrost site management (1)
Gets the property value of a column in the list collection object
On fedlearner, the latest open source federated machine learning platform of byte
Overview of the most complete anomaly detection algorithm in history
Explanation of Z-index attribute
随机推荐
csdn bug11:待加
csdn bug9:待加
C++ STL容器篇
异常:Invalid or unexpected token
Android quick shutdown app
Hong Kong listed companies transfer cards to acquire 42.5% equity of chuangxinzhong and plan to speed up the distribution of marketing services
Notes on Python cookbook 3rd (2.2): String start or end match
gnu汇编-基本数学方程-乘法
[paper reading notes] network embedding with attribute refinement
Day85: Luffy: shopping cart switching price according to different validity period & shopping cart deletion operation & price settlement & foreplay of order page
走进C# abstract,了解抽象类与接口的异同
仅发送options请求,没有发送post解决方案
编码风格:Mvc模式下SSM环境,代码分层管理
“wget: 无法解析主机地址”的解决方法
The solution of polar experience insensitive verification
Explanation of Z-index attribute
Graph undirected graph
Incomplete Polyfill of proxy
Coding style: SSM environment in MVC mode, code hierarchical management
On fedlearner, the latest open source federated machine learning platform of byte