Two numbers - the algorithm

Two numbers and

Problem Description

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

Example:

given nums = [2, 7, 11, 15], target = 9

Because nums[0] + nums[1] = 2 + 7 = 9
so return[0, 1]

problem analysis

Acquire a number, then let a number, do the match, and was targetto return to index

Code

暴力法

public:
    vector<int> twoSum(vector<int>& nums, int target) {
vector<int> v(2);
        for(int i = 0; i < nums.size(); ++i)
        {
            for(int j = i + 1; j < nums.size(); ++j)
            {
                if(nums.at(i) + nums.at(j) == target)
                {
                    v.at(0) = i;
                    v.at(1) = j;
                    return v;
                }
            }
        }
        return v;
    }
};

operation result

输入

[2,7,11,15]

9

输出

[0,1]

to sum up

The use of brute force problem, the use of two cycles, of course, the method may be employed in the hash table, the index number of each table corresponding thereto is stored, the number before each take, matching hash table to see if there compliance therewith can and as targetthe number has its index is returned, if any, added to the hash table, start the next looking for.

Published 59 original articles · won praise 5 · Views 5057

Guess you like

Origin blog.csdn.net/qq_38496329/article/details/104077648
Recommended