Leetcode Brush title Record-two Sum

Source: Internet
Author: User

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.

Problem Solving Ideas:

Use target minus each number in the array to get the array of difference array, with the example in the original question: {2,7,11,15} corresponds to the difference array of {7,2,-1,,6}, and then traverse the original array, if the difference array also contains this number and the corresponding index is not equal, Returns the index of the original array in the value index and the array of difference values. In order to make the time complexity O (n), the difference data needs to be stored in the form of a hash map.

Problem Solving Source:

1 classSolution {2  Public:3vector<int> Twosum (vector<int>& Nums,inttarget) {4map<int,int>Finder;5         intIndex1 =-1;6         intIndex2 =-1;7          for(intI=0; I<nums.size (); ++i) {8             int_num = target-Nums[i];9Finder.insert (map<int,int>:: Value_type (_num, i));Ten         } One          for(intI=0; I<nums.size (); ++i) { Amap<int,int>:: iterator ITR; -ITR =Finder.find (Nums[i]); -             if(itr!=Finder.end ()) { the                 intj =Finder[nums[i]]; -                 if(i!=j) { -Index1 =min (i, j); -Index2 =Max (I, j); +                      Break; -                 } +             } A         } atvector<int>rst; -Rst.push_back (index1+1); -Rst.push_back (index2+1); -         returnrst; -     } -};

Leetcode Brush title Record-two Sum

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.