Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/two-sum
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.
You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.
Example:
Given nums = [2, 7, 11, 15], target = 9
Because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]
Violence: Do not say. O (n * n)
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int i,j; for(i=0;i<nums.size()-1;i++) { for(j=i+1;j<nums.size();j++) { if(nums[i]+nums[j]==target) { return {i,j}; } } } return {i,j}; }; };
The key is O (n) made out
class Solution { public : Vector < int > twoSum (Vector < int > the nums &, int target) { Map < int , int > A; // provide one of the hash Vector < int > B ( 2 , - . 1 ); // for carrying a result, a size of the initialization container 2, a value of -1 B for ( int I = 0 ; I <nums.size (); I ++ ) { IF (a.count (target-the nums [I] )> 0 ) { B [ 0] A = [target- the nums [I]]; B [ . 1 ] = I; BREAK ; } A [the nums [I]] = I; // turn into the map for obtaining the results subscript } return B ; }; };