The sum of the two numbers is equal to the target value

topic:

Given an integer array and a target value, find two numbers in the array that sum to the target value, and return these two numbers through another array. It can be assumed that each input corresponds to only one answer, and the same elements cannot be reused.
Example:
Given nums = [2, 7, 11, 15], target = 9
returns [0, 1] because nums[0] + nums[1] = 2 + 7 = 9

the first method:

Using a two-layer for loop, if the sum of the two numbers is equal to the target value, two indices are returned, so that each data can be traversed, but the time complexity is O(N^2), which is relatively high.
Code:

void TwoSum(vector<int>& v1, vector<int>& v2, int key)
{
    for (int i = 0; i < v1.size(); i++)
    {
        for (int j = 0; j < v1.size(); j++)
        {
            if (v1[i] + v1[j] == key)
            {
                v2.push_back(i);
                v2.push_back(j);
                return;
            }
        }
    }
}

The second method:

This method is for sorted arrays. If the elements of the array are not in ascending order, they need to be sorted first.
The second method, we are like this, we first create two indexes begin and end, which point to the smallest element and the largest element in the array respectively, add up these two numbers, if the sum is equal to the key, we return directly The index of these two data; if the sum of the two numbers is less than the key, then begin++; if the sum of the two numbers is greater than the key, then end–; this cycle until the begin and end meet.
Code:

void TwoSum(vector<int>& v1, vector<int>& v2, int key)//这个必须是升序的
{
    int begin = 0;
    int end = v1.size() - 1;
    while (begin < end)
    {
        if (v1[begin] + v1[end] == key)
        {
            v2.push_back(begin);
            v2.push_back(end);
            return;
        }
        else if (v1[begin] + v1[end] < key)
            begin++;
        else
            end--;
    }
}

Third method:

We first create an unordered_map, assuming that the array given by the question is v1, we subtract v1[0] from the key, if the result obtained is in the map, it means that we have found the two numbers required by the question, if the result obtained is not in the map , we insert v1[0] into the map along with its index. Repeat the cycle to get the result.
Because the efficiency of looking up in the hash is O(1) is very high, so we can complete this problem with high efficiency.
Code:

void TwoSum(vector<int>& v1, vector<int>& v2, int key)
{   //哈希, 下标i作为value传入
    unordered_map<int, int> m;
    for (int i = 0; i < v1.size(); i++)
    {
        unordered_map<int, int>::iterator it = m.find(key - v1[i]);
                                        //没找到返回end(),找到了返回数据对应的迭代器
        if (it != m.end())//找到了
        {
            v2.push_back(m[key - v1[i]]);
            v2.push_back(i);    
        }
        else//没找到插入
            m.insert({ v1[i], i });
    }
}

Test program and running results:
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325668993&siteId=291194637