Leetcode-two sum

Source: Internet
Author: User

Question:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twosum shocould return indices of the two numbers such that they add up to the target, where index1 must be less than index2. please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input wowould have exactly one solution.

Input: Numbers = {2, 7, 11, 15}, target = 9
Output: index1 = 1, index2 = 2

Analysis 1:

The question must be very clear, give an integer array (there is no order, there may be duplicate values, and there may be negative numbers), find the number of two of them, make their sum the target given. Returns the subscript of the two numbers in sequence. Each array has only one set of answers.

After reading the question at the beginning, I wrote two for loops. The Code is as follows. Then the Code was submitted happily, and the result was tragic.

The system gave the error time limit exceeded. The number of elements in the test array is 10000. Thanks for the two for loops.

    vector<int> twoSum(vector<int> &numbers, int target) {    vector<int> indexs;    vector<int> res;    bool flag = true;        for (int i=0; i<numbers.size()-1 && flag; i++)    {    for (int j=i+1; j<numbers.size(); j++)    {    if(numbers[i] + numbers[j] == target)    {    res.push_back(i+1);    res.push_back(j+1);    flag = false;    break;    }    }    }        return res;    }

Analysis 2:

This problem seems to be looking for two numbers, but it can be converted into a number problem. For an array with a large number of elements, you must use hashmap to quickly find a number. The code for the second algorithm is as follows:

    vector<int> twoSum(vector<int> &numbers, int target) {    vector<int> res(2,0);    unordered_map<int, int> numbersMap;        for(int i=0; i<numbers.size(); i++)    numbersMap[numbers[i]] = i;        unordered_map<int, int>::const_iterator iter = numbersMap.end();    for (int i=0; i<numbers.size(); i++)    {    int minus = target - numbers[i];    iter = numbersMap.find(minus);    if (iter != numbersMap.end() && iter->second != i)    {    if (i < iter->second)    {    res[0] = i+1;    res[1] = iter->second + 1;    }    else    {    res[0] = iter->second + 1;    res[1] = i + 1;    }        }    }        return res;    }

The keys and values of unordered_map <int, int> are integer data. I use the data in numbers as the key, and then use the corresponding subscript as the value to create and initialize a map. One problem here is that numbers may have the same value. The same value is the same as the key in map, but the corresponding value is different. Unordered_map should handle such conflicts internally, so don't worry about this problem.

Note that when finding the number (minus) to be searched, you must determine whether it is the same number as number [I] based on the subscript. If the subscript is the same, but not found yet.

  if (iter != numbersMap.end() && iter->second != i)

The following is the complete code, including testing:

# Include <iostream> # include <vector> # include <unordered_map> using namespace STD; vector <int> twosum (vector <int> & numbers, int target) {vector <int> res (); // creates and initializes a hashmap. Each value of numbers is used as the key, and value is the corresponding subscript. // The values in numbers may be the same, but the subscript corresponding to the same value is different. Unordered_map <int, int> numbersmap; For (INT I = 0; I <numbers. size (); I ++) numbersmap [numbers [I] = I; unordered_map <int, int >:: const_iterator iter = numbersmap. end (); For (INT I = 0; I <numbers. size (); I ++) {// calculate the difference and use the difference value as the key to find int minus = target-numbers [I]; iter = numbersmap. find (minus); If (ITER! = Numbersmap. End () & ITER-> second! = I) // check whether it is found and whether it is the same value {if (I <ITER-> second) {res [0] = I + 1; res [1] = ITER-> second + 1;} else {res [0] = ITER-> second + 1; Res [1] = I + 1 ;}}} return res;} int _ tmain (INT argc, _ tchar * argv []) {int target = 9; vector <int> numbers; numbers. push_back (2); numbers. push_back (7); numbers. push_back (11); numbers. push_back (15); vector <int> res = twosum (numbers, target); // test result for (INT I = 0; I <res. size (); I ++) cout <res [I] <""; cout <Endl; return 0 ;}

I don't know much about hashmap. I need to study it carefully!


Contact Us

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.