[Leetcode] Both Sum (c + +)

Source: Internet
Author: User

Topic:

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

The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.

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

Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2

Tag:

Array; Hash Table

Experience:

Ah haha, this problem once success, although the version is different from the following, but the idea is the same.

This problem is very clever with the map, because it is to find two numbers together can be target, so encountered a number, you know it should be with whom to make up the right, although do not know whether the number can be found in the array exists in or exist somewhere. Make a map of <number, Index>, and record where each number appears. Check the numbers one after the other to see if the number he's trying to make is already there.

P.S. My map has the number that I want to find directly. For example Target=9, now in position 0 met 2, then I will save a map[9-2]=0, and then check the time can go directly to the keys to find whether there is 7.

1 classSolution {2  Public:3vector<int> Twosum (vector<int> &numbers,inttarget) {4             intn =numbers.size ();5vector<int>result;6map<int,int>index;7              for(inti =0; I < n; i++) {8                 if(Index.count (numbers[i])! =0) {9                     //if existsTenResult.push_back (Index[numbers[i]) +1); OneResult.push_back (i +1); A                      Break; -                 }  -Index[target-numbers[i]] =i; the             } -             returnresult; -     } -};

[Leetcode] Both Sum (c + +)

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.