# Leetcode 1. A Sum array of

Source: Internet
Author: User

1. The Sum of the

Given an array of integers, return indices of the both numbers such that they add-to a specific target.

You may assume this each input would has exactly one solution.

Example:

`Given nums = [2, 7, one, 2], target = 9,because nums[0] + nums[1] = + 7 = 9,return [0, 1].`

Main topic:

Finds the sum of 2 elements in an array and equals the number of targets, outputting the subscripts of these two elements.

Ideas:

The stupidest way to deal with it is to double-cycle it. Time complexity O (n*n).

The code is as follows:

`Class solution {public:    vector<int> twosum (vector<int>&  nums, int target)  {        vector<int>  result;        int i,j;         for (I = 0; i < nums.size (); i++)          {            for (j = i+1;  j < nums.size (); j + +)              {                if (nums [I] + nums[j] == target)                  {                  &nbsP;  result.push_back (i);     result.push_back (j);                     break;                 }             }        }         return result;    }};`

Refer to the practices of others: Https://discuss.leetcode.com/topic/3294/accepted-c-o-n-solution

Using the key value of the map, the element is the key, the index of the element to do the value.

`Vector<int> twosum (Vector<int> &numbers, int target) {     //key is the number and value is its index in the  vector.    unordered_map<int, int> hash;     vector<int> result;    for  (int i = 0; i <  numbers.size ();  i++)  {        int numbertofind  = target - numbers[i];             //if numberToFind is found in map, return them         if  (Hash.find (Numbertofind)  != hash.end ())  {                          result.push_back (Hash[numbertofind]);             result.push_back (i );                         return result;        }             //number was not found.  put it in the map.        hash[numbers[i]] =  i;    }    return result;}`

2016-08-11 15:02:14

Leetcode 1. A Sum array of

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.