Algorithm questions daily practice---Day 80: The sum of two numbers

Get into the habit of writing together! This is the 15th day of my participation in the "Nuggets Daily New Plan·April Update Challenge", click to view the details of the event .

1. Problem description

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

You can assume that there will only be one answer for each input. However, the same element in the array cannot be repeated in the answer.

You can return answers in any order.

Topic link: The sum of two numbers

Second, the subject requirements

Example 1

输入: nums = [2,7,11,15], target = 9
输出: [0,1]
解释: 因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
复制代码

Example 2

输入: nums = [3,2,4], target = 6
输出: [1,2]
复制代码

visit

1.哈希表、暴力
2.建议用时10~25min
复制代码

3. Problem Analysis

1. Violence Laws

Generally speaking, computer 1s can run 1 e + 8 1e+8 times, the scope of this question is 1 e + 4 1e+4 , the double for loop will not time out, first come violently to engage in a wave.

If there are two numbers, then I will do two for loops and search and judge one by one.

2. Hash

What does hash mean?

Store the subscript of the array element in the hash table, and determine whether target-v[i]the result of the target value exists or not. If it exists, return the subscript, and there is no element subscript to be added.

Fourth, the encoding implementation

1. Violence Laws

class Solution {
public:
    vector<int> twoSum(vector<int>& v, int target) {
        int i,j,n=v.size();//初始化
        for(i=0;i<n;i++)//双重for循环
        {
            for(j=i+1;j<n;j++)
            {
                if(v[i]+v[j]==target)//找到位置输出
                    return {i,j};
            }
        }
        return {-1,-1};
    }
};
复制代码

2. Hash

class Solution {
public:
    vector<int> twoSum(vector<int>& v, int target) {
        int i,j,n=v.size();//初始化
        map<int,int>m;//哈希表
        for(i=0;i<n;i++)
        {
            auto it=m.find(target-v[i]);//目标数字
            if(it!=m.end())//成功找到,输出
                return {it->second,i};
            m[v[i]]=i;
        }
        return {-1,-1};
    }
};

复制代码

5. Test results

0.png

3.png

Guess you like

Origin juejin.im/post/7086632377035784223