Leetcode--twosum

Source: Internet
Author: User

Solving methods

1. Violence solving method (time complexity O (n*n)): Iterate through each element first, then traverse the remaining elements to see if the x+y=target is satisfied .

2, we can reduce the time complexity to O (n)by mapping the values to the index using hash.

#include <iostream>#include<windows.h>#include<time.h>#include<vector>#include<unordered_map>using namespacestd;classsolution{ Public: Vector<int>twosum (vector<int> &numbers,inttarget) {Unordered_map<int,int>mapping; Vector<int>result;  for(inti =0; I < numbers.size (); i++) {Mapping[numbers[i]]=i; }         for(inti =0; I < numbers.size (); i++)        {            Const intGap = target-Numbers[i]; if(Mapping.find (GAP)!=mapping.end () &&mapping[gap]>i) {result.push_back (i+1); Result.push_back (Mapping[gap]+1);  Break; }        }        returnresult; }};intMain () {solution sum; Vector<int>numbers= {2,7, One, the}; inttarget =9;    time_t Clockbegin, Clockend; Clockbegin=clock ();    Sum.twosum (numbers, target); Clockend=clock (); //cout << "spend time:" << clockend-clockbegin << Endl;printf"%ld\n", clockend-clockbegin);    GetChar (); return 0;}

Note: The return type is a result sorted by index size, used unordered_map for lookup, and the complexity is O (n)

This method is wrong if the data is destroyed by using the current sort, which requires the index of the data to be returned.

If the given data is already sorted, use the dichotomy method to find and then determine the time complexity of O (Nlogn).

Leetcode--twosum

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.