首页 > 其他 > 详细

[LeetCode] Two Sum

时间:2015-06-08 19:10:50      阅读:284      评论:0      收藏:0      [点我收藏+]

This is a classic problem for hash table. The basic idea is to maintain a hash table for each element in nums, using the element as key and its index (in this problem, 1-based) as value. Then for each num of nums, search for target - num in the hash table. If it is found and is not the same as num, then we are done. Notice that the problem statement has excluded the case of duplicates by stating that "each input would have exactly one solution".

Now you may quickly write down the following code.

 1 vector<int> twoSum(vector<int>& nums, int target) {
 2     vector<int> ans;
 3     unordered_map<int, int> mp;
 4     for (int i = 0; i < nums.size(); i++)
 5         mp[nums[i]] = i + 1;
 6     for (int i = 0; i < nums.size(); i++) {
 7         if (mp.find(target - nums[i]) != mp.end() && mp[target - nums[i]] != i + 1) {
 8             ans.push_back(i + 1);
 9             ans.push_back(mp[target - nums[i]]);
10             return ans;
11         }
12     }
13 }

Notice the above code has two for loops to iterate over nums. In fact, the process of building the hash table and searching in it can be done in one pass. Each time before you add a num to mp, just search for target - num first. The code now becomes as follows.

 1 vector<int> twoSum(vector<int>& nums, int target) {
 2     vector<int> ans;
 3     unordered_map<int, int> mp;
 4     for (int i = 0; i < nums.size(); i++) {
 5         if (mp.find(target - nums[i]) != mp.end() && mp[target - nums[i]] != i + 1) {
 6             ans.push_back(mp[target - nums[i]]);
 7             ans.push_back(i + 1);
 8             return ans;
 9         }
10         mp[nums[i]] = i + 1; 
11     }
12 }

[LeetCode] Two Sum

原文:http://www.cnblogs.com/jcliBlogger/p/4561484.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!