[LeetCode] Two Sum

本文介绍了如何优化两数之和算法,通过一次遍历实现,利用哈希表存储元素及其索引来提高效率,解决了经典问题,并提供了改进后的代码实现。

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 }

转载于:https://www.cnblogs.com/jcliBlogger/p/4561484.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值