Twosum (c + +)

Source: Internet
Author: User

1vector<int> Twosum (vector<int> &numbers,inttarget)2 {3     //Key is the number and value are its index in the vector.4unordered_map<int,int>Hash; Unordered_map is an unordered associative container5vector<int>result;6      for(inti =0; I < numbers.size (); i++) {7         intNumbertofind = target-Numbers[i];8 9             //if Numbertofind is found in map, return themTen         if(Hash.find (numbertofind)! =Hash.end ()) {//find () returns an iterator that points to the first element of value in the interval [first,last] (hash ordinal), and returns the last if not found One                     //+1 because indices is not zero based AResult.push_back (Hash[numbertofind] +1);//push_back (t) Insert T in front of A.end () -Result.push_back (i +1);  -             returnresult; the         } -  -             //Number is not found. Put it in the map. -Hash[numbers[i]] =i; +     } -     returnresult; +}

Unordered associative containers are: unordered_set unordered_multiset unordered_map unordered_multimap, which use keys and hash tables so that data can be accessed quickly. Without the Lower_bound and upper_bound of the ordered associative containers, the comparison is based on the concept of equals.

Twosum (c + +)

Related Article

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.