Two Sum [leetcode], twosumleetcode

Source: Internet
Author: User

Two Sum [leetcode], twosumleetcode

I haven't written a blog for a long time. I recently refreshed the leetcode and found that I had written quite good code before. I added some of my latest thoughts, so I made a po.

There are two ways to solve this problem. One is sorting + O (n) search.

The other is Hash.

The Hash method code is as follows:

    vector<int> twoSum(vector<int> &numbers, int target) {        map<int, int> num_index;        vector<int> res;        for (int index = 0; index < numbers.size();index++)        {            if (num_index.find(target - numbers[index]) != num_index.end())            {                res.push_back(num_index[target - numbers[index]] + 1);                res.push_back(index + 1);                return res;            }            num_index[numbers[index]] = index;        }        return res;    }

Note: First find another number and store it in the hash.


C ++ leetcode always says that the compilation is wrong. The key is that I don't even have 77th lines, only those lines ......

Neither leetcode can define the main function.
You need to construct a Solution class

The main of the 77 rows of redefine happens to be the main function of leetcode used to test the Solution you write.

What is leetcode?

There are many programming and interview questions, which can be compiled and run online. It is difficult. If you can do it all by yourself, it is very helpful for large companies. I just did the questions there.

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.