当前位置:网站首页>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 .
边栏推荐
- Develop those things: go plus c.free to free memory, and what are the reasons for compilation errors?
- Adrnoid开发系列(二十五):使用AlertDialog创建各种类型的对话框
- Comparison of various development methods of applets - cross end? Low code? Native? Or cloud development?
- CXF call reports an error. Could not find conduct initiator for address:
- Adrnoid Development Series (XXV): create various types of dialog boxes using alertdialog
- Install Fedora under RedHat
- 二叉树(Binary Tree)
- 为什么市场需要低代码?
- Solution: prompt "unsupported video format" when inserting avi format video into the message
- Network security - phishing
猜你喜欢
leetcode-520. 检测大写字母-js
Transform XL translation
Introduction to redis and jedis and redis things
小程序多种开发方式对比-跨端?低代码?原生?还是云开发?
微信论坛交流小程序系统毕业设计毕设(1)开发概要
JMeter interface automated test read case, execute and write back result
Use JfreeChart to generate curves, histograms, pie charts, and distribution charts and display them to jsp-2
The wonderful relationship between message queue and express cabinet
二叉树(Binary Tree)
Specific method example of V20 frequency converter manual automatic switching (local remote switching)
随机推荐
Network security - joint query injection
USB(十五)2022-04-14
2021-01-12
[record of question brushing] 3 Longest substring without duplicate characters
Kubernetes' simplified data storage storageclass (creation, deletion and initial use)
Network security CSRF
Cascade-LSTM: A Tree-Structured Neural Classifier for Detecting Misinformation Cascades-KDD2020
网络安全-永恒之蓝
How to operate DTC community?
Talk about DART's null safety feature
OC variable parameter transfer
Installing vmtools is gray
嵌入式音频开发中的两种曲线
Database daily question --- day 22: last login
Solution: prompt "unsupported video format" when inserting avi format video into the message
php 使用阿里云存储
三菱PLC slmp(mc)协议
Use JfreeChart to generate curves, histograms, pie charts, and distribution charts and display them to jsp-2
Line test - graphic reasoning - 1 - Chinese character class
ArcGIS: field assignment_ The attribute table field calculator assigns values to fields based on conditions