leetcode 1. The sum of two numbers (hash table)

insert image description here
insert image description here
The comments really made me laugh, I can't help it

Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value target in the array, and return their array subscripts.

You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: 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]

hint:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
There can only be one valid answer

Code: (hash table)

class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    
    
        unordered_map<int,int> hashtable;
        int n=nums.size();
        for(int i=0;i<n;++i){
    
    
            auto it=hashtable.find(target-nums[i]);
            if(it!=hashtable.end())//迭代器没有走到最后说明在中间的位置就找到了,所以可以直接返回
                return {
    
    i,hashtable[target-nums[i]]};
            hashtable[nums[i]]=i;
        }
        return {
    
    };
    }
};

The interior of unordered_map is implemented with a hash table, and the internal elements are disordered and disordered.

Code idea:
Find whether there is an element of target-nums[i] in the hash table at the beginning, if there is, that is, the iterator has not reached the end, then directly return the current subscript and the key value in the hash table to target The value of -nums[i] is the subscript of target-nums[i]; if it is not found, it means that there is no match with it before this number, and the match may be behind, so you must first Stored in the hash table, it is easy to find elements later.

The first int of unordered_map<int,int> in the hash table is the key value key, and the second int is the value value.

The value of the hash table can be used like hashmap[x]=y, where x represents the key value, and y is the value corresponding to x.
In this function, the key value is used to save the value in the array, and the value is used to save the corresponding subscript value.

Suppose the order of elements in nums is {2,11,7,.15}
when i=0, it is 2 at the beginning, and 9-2=7 is not in the hash table, so add {2,0} to the hash table middle. This means that there is no value before 2 and it adds up to 9, and then continue to look backward.
When i=1, 9-11=-2 is not in the hash table, so add {11,1} to the hash table.
When i=2, 9-7=2 is in the hash table, and the iterator is not at the end at this time, so the if statement is executed to return the current subscript and the subscript of target-nums[i] in the hash table.



Guess you like

Origin blog.csdn.net/xiatutut/article/details/127322510