[LeetCode] 2011-03-13 Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


Use hash table to save all the numbers. The pre-processing takes O(n), go through all the number is another O(n).

Using "unordered_map",

use [ ] to add (and update) value, or use insert(make_pair(key, value) instead.

use find(key) to search hash, in this case, because all the values must be greater than 0 (i + 1, i starts from 0), so use [ ] is a more cleaner way, by using [ ], if the key is no exist, it will return 0.

need to check the new index is not equal to the search index.


<span style="font-size:14px;">class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        unordered_map<int, int> cache;
        vector<int> res;
        
        for (int i = 0; i < numbers.size(); i ++) {
            cache[numbers[i]] = i + 1;
        }
        
        for (int i = 0; i < numbers.size(); i ++) {
            int index = cache[target - numbers[i]];
            if (index > 0 && index != (i + 1)) {
                res.push_back(i + 1);
                res.push_back(index);
                break;
            }
        }
        
        return res;
    }
};</span>


This approach passes all the test, but there is a potential bug. Consider case [0, 2, 3, 0], 0, cache[0] gives us "4", which is the second value of the key "0", if interviewee want larger index display first, then the bug will be critical. A cleaner and neat approach is here:


<span style="font-size:14px;">class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        unordered_map<int, int> cache;
        vector<int> res;
        
        for (int i = 0; i < numbers.size(); i ++) {
            int val = target - numbers[i];
            
            if (cache[val] > 0) {
                res.push_back(cache[val]);
                res.push_back(i + 1);
                break;
            }
            
            cache[numbers[i]] = i + 1;
        }
        
        return res;
    }
};</span>

What if there are more than one solution? Consider case [0, 0, 0], 0, the output shall be [[1,2],[1,3],[2,3]].


<span style="font-size:14px;">class Solution {
public:
    void twoSum(vector<int> &numbers, int target) {
        unordered_map<int, vector<int>> indexCache;
        
        for (int i = 0; i < numbers.size(); i ++) {
            unordered_map<int, vector<int>>::iterator iter = indexCache.find(numbers[i]);
            if (iter != indexCache.end()) {
                iter->second.push_back(i + 1);
            } else {
                indexCache[numbers[i]] = vector<int> (i + 1);
            }
        }
        
        for (int i = 0; i < numbers.size(); i ++) {
            int val = target - numbers[i];
            if (indexCache.find(val) != indexCache.end()) {
                for(int j = 0; j < indexCache[val].size(); j ++) {
                    int index = indexCache[val][j];
                    if (index > (i + 1)) {
                        cout << (i + 1) << " " << index;
                    }
                }
            }
        }
    }
};</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值