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.