当前位置:网站首页>1. Sum of two numbers
1. Sum of two numbers
2022-07-07 23:15:00 【JUSTfFUN】
Sum of two numbers (C++)
Topic introduction
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 .
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/two-sum
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
Enumeration
Core tools
- Use STL in find() and distance()
Their thinking
- Use the target value target Subtract array vector The first element in
- Judge whether the difference exists , And is not equal to this element ( The title requires that the same element cannot be repeated )
- about vector The elements in perform this operation in turn
Source code of problem solving
// 2021.07.13
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// Sort , Easy to use binary_search() Algorithm
// sort(nums.begin(), nums.end()); error
vector<int>::iterator first = nums.begin();
// Record subscripts
int i = -1;
int j = -1;
for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++)
{
// Record target The difference from the current element
int cha = target - (*it);
// If the difference exists, use cha_weizhi Save its location
vector<int>::iterator cha_weizhi = find(nums.begin(), nums.end(), cha);
// Judge whether the difference exists
if (cha_weizhi != nums.end() && cha_weizhi != it)
{
// Use distance The algorithm returns the subscript
i = distance(first, it);
j = distance(first, cha_weizhi);
return {
i, j};
}
}
return {
};
}
};
/* * notes : * distance(): * grammar : * template<class InputIterator> * typename iterator_traits<InputIterator>::difference_type distance (InputIterator first,InputIterator last); * This function will return [first, last) The number of elements contained in the range . */
There is an error
The sort operation caused an error
For the use of binary_find() The algorithm improves the search speed , You need to sort the sequence
error :vector The element position changes after sorting , When the subscript is returned, the subscript after sorting is returned
Condition judgment error
if (cha_weizhi != nums.end() && cha_weizhi != it)
Missing in the condition judgment of this statement cha_weizhi != it
Make the title “ The same element in the array cannot be repeated in the answer ” Requirements not met
hash Table method
advantage
- Use map Find index find target - x The time complexity of is O(1), Instead, use enumeration to find target -x The time complexity of is O(N^2)
- Using enumeration method requires judging that two numbers are not themselves , While using map Because its key value is unique , You don't have to judge
Core tools
- unordered_map : No automatic sorting map
The core idea
- Create a unordered_map( Sorting will change the subscript of array elements )
- use unordered_map Key to store vector The elements of , use unordered_map To store vector Subscript of element ( Because it is convenient to search for keys , Feel free to put elements into keys )
- Determine whether there is a return subscript in the difference {it->second, i}
- Since this method does not traverse twice, there will be no problem of using the same element twice
Source code of problem solving
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]); // When hashtable When not assigned it = hashtable.end();
if (it != hashtable.end()) {
return {
it->second, i};
}
hashtable[nums[i]] = i; // about hashtable Perform assignment operation , bring vector All unqualified elements in the will put the element value in hashtabe In the key of ( Easy to find again ), Put the subscripts in the original order hashtable Of ( Convenient return subscript )
}
return {
};
}
};
author :LeetCode-Solution
link :https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-solution/
source : Power button (LeetCode)
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .
边栏推荐
- Quelles sont les similitudes et les différences entre les communautés intelligentes et les villes intelligentes?
- oc 可变參数传递
- 小程序多种开发方式对比-跨端?低代码?原生?还是云开发?
- Anta DTC | Anta transformation, building a growth flywheel that is not only FILA
- 海内外技术人们“看”音视频技术的未来
- I wish you all the best and the year of the tiger
- JS triangle
- 定位到最底部[通俗易懂]
- 为什么市场需要低代码?
- 微信论坛交流小程序系统毕业设计毕设(5)任务书
猜你喜欢

Specific method example of V20 frequency converter manual automatic switching (local remote switching)

Binary tree

30讲 线性代数 第五讲 特征值与特征向量

ArcGIS:矢量要素相同字段属性融合的两种方法

UE4_UE5蓝图command节点的使用(开启关闭屏幕响应-log-发布全屏显示)

ArcGIS: two methods of attribute fusion of the same field of vector elements

Technology at home and abroad people "see" the future of audio and video technology

Cascade-LSTM: A Tree-Structured Neural Classifier for Detecting Misinformation Cascades-KDD2020

JMeter-接口自动化测试读取用例,执行并结果回写

Lecture 30 linear algebra Lecture 5 eigenvalues and eigenvectors
随机推荐
30讲 线性代数 第五讲 特征值与特征向量
OC variable parameter transfer
[network] Introduction to C language
微信论坛交流小程序系统毕业设计毕设(4)开题报告
【刷题记录】3. 无重复字符的最长子串
Are the microorganisms in the intestines the same as those on the skin?
小程序多种开发方式对比-跨端?低代码?原生?还是云开发?
Unity3D学习笔记6——GPU实例化(1)
Comparison of various development methods of applets - cross end? Low code? Native? Or cloud development?
ArcGIS:矢量要素相同字段属性融合的两种方法
网格(Grid)
定位到最底部[通俗易懂]
Wechat forum exchange applet system graduation design completion (4) opening report
【微服务|SCG】gateway整合sentinel
Mitsubishi PLC SLmP (MC) protocol
USB(十五)2022-04-14
网络安全-CSRF
Use JfreeChart to generate curves, histograms, pie charts, and distribution charts and display them to JSP-1
FPGA基础篇目录
Wechat forum exchange applet system graduation design (5) assignment