Leetcode - the sum of two numbers

Given an array of integers and a target value, find two numbers in the array that sum to the target value.

You can assume that each input corresponds to only one answer, and that the same elements cannot be reused.

Example:

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

because nums[0] + nums[1] = 2 + 7 = 9
So return [0, 1]

 My own idea is as follows: subtract the elements in the container nums with target in turn, and put them in another container b with the corresponding positions. Since the same elements cannot be reused, then compare whether the elements in b are in nums in turn. appears, and if it does, we've found two locations. In addition, it is required to return a pair of numbers. We need to create an additional container c, and put the found position into the container c for return.

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target)
    {
        vector<int>b,c;
        for(int i=0;i<nums.size();i++)
        {
             b.push_back(target-nums[i]);
        }
        for(int i=0;i<b.size();i++)
            for(int j=0;j<nums.size();j++)
            {
                if(b[i]==nums[j])
                {
                    if(i!=j)
                    {
                        c.push_back(i);
                        c.push_back(j);
                        return c;
                    }
                }
            }
    }
};

So is there a better algorithm? Of course there is. The time complexity of the above algorithm has reached o(n^2). After reference, the excellent algorithm is specially recorded as follows

vector<int> twoSum(vector<int>& nums, int target)
{
  unordered_map<int, int> m;
  vector<int> c;
  for (int i = 0; i < nums.size(); ++i)
  {
    if (m.count(target - nums[i]))
    {
      c.push_back(m[target-nums[i]]);
      c.push_back(i);
      return c;
    }
    m[nums[i]] = i;
  }
}

The count function is included in the algorithm header file, count(first, end, pre), in the parameter first represents the starting position of the query, which is an iterator, end represents the ending position of the query, and is also an iterator, and pre is The element to query, returns the number of occurrences of the element. The count function is similar to the find function, but the find function returns an iterator for the element.

The value returned by count in the above program is 1 or 0, because in unorder_map, an element is only allowed to appear once, and the same element will be overwritten. If target-nums[i] is queried, return i and the found position, such as {2,7,4,11}, target=6.map will get (2,0)(7,1)(4, 2), it can be found that target-4=2, which has been found in the map, return to the position where it was found (it must be in front, so return first), and then return to this position.

Guess you like

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