当前位置:网站首页>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 .
边栏推荐
猜你喜欢
Comparison of various development methods of applets - cross end? Low code? Native? Or cloud development?
Inftnews | the wide application of NFT technology and its existing problems
Talk about the design and implementation logic of payment process
消息队列与快递柜之间妙不可言的关系
JMeter-接口自动化测试读取用例,执行并结果回写
Develop those things: go plus c.free to free memory, and what are the reasons for compilation errors?
[microservices SCG] gateway integration Sentinel
UE4_UE5蓝图command节点的使用(开启关闭屏幕响应-log-发布全屏显示)
海内外技术人们“看”音视频技术的未来
Anta DTC | Anta transformation, building a growth flywheel that is not only FILA
随机推荐
Anta DTC | Anta transformation, building a growth flywheel that is not only FILA
高级程序员必知必会,一文详解MySQL主从同步原理,推荐收藏
Solution: prompt "unsupported video format" when inserting avi format video into the message
14、 Two methods of database export and import
微信论坛交流小程序系统毕业设计毕设(5)任务书
Wechat forum exchange applet system graduation design (5) assignment
【编译原理】词法分析设计实现
Software test classification
Talk about DART's null safety feature
Circumvention Technology: Registry
Clean C disk
网络安全-对操作系统进行信息查询
网络安全-永恒之蓝
Network security - phishing
Binary tree
Statistical method for anomaly detection
Dynamics 365 find field filtering
Adrnoid开发系列(二十五):使用AlertDialog创建各种类型的对话框
Brush question 4
十三、系统优化