Make writing a habit together! This is the 15th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

I. Problem description

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

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

You can return the answers in any order.

The sum of two numbers

Two, the title requirements

Sample 1

Input: nums = [2,7,11,15], target = 9 output: [0,1]Copy the code

The sample 2

Input: nums = [3,2,4], target = 6Copy the code

inspection

1. Hash table, violence 2. It is recommended to use 10 to 25 minutesCopy the code

Third, problem analysis

1. The method of violence

In general, computer 1s can run 1e+ 81E + 81E +8 times, which is the range of 1e+ 41E + 41E +4.

Two numbers, so I’m just going to double the for loop, and I’m just going to search one by one.

2. A hash

What does hash mean?

Select target-v[I], target-v[I], target-v[I], target-v[I], target-v[I]

Four, coding implementation

1. The method of violence

class Solution {
public:
    vector<int> twoSum(vector<int>& v, int target) {
        int i,j,n=v.size(a);/ / initialization
        for(i=0; i<n; i++)// Double for loop
        {
            for(j=i+1; j<n; j++) {if(v[i]+v[j]==target)// Find the position output
                    return{i,j}; }}return {- 1.- 1}; }};Copy the code

2. A hash

class Solution {
public:
    vector<int> twoSum(vector<int>& v, int target) {
        int i,j,n=v.size(a);/ / initialization
        map<int.int>m;/ / a hash table
        for(i=0; i<n; i++) {auto it=m.find(target-v[i]);// Target number
            if(it! =m.end())// Successfully found, output
                return {it->second,i};
            m[v[i]]=i;
        }
        return {- 1.- 1}; }};Copy the code

V. Test results