Two Sum

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solutions

My solution

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, vector<int>> hash;
        for(int i = 0; i < nums.size(); ++i)
            hash[nums[i]].push_back(i);
        vector<int> ans(2);
        for(int i = 0; i < nums.size(); ++i){
            auto it = hash.find(target - nums[i]);
            if(it != hash.end() && (it->first != nums[i] || it->second.size() == 2)){
                ans[0] = i;
                ans[1] = it->second.back();
                break;
            }
        }
        return ans;
    }
};

A better solution

One pass. Handle the case where 2 * nums[i] == 2 * nums[j] == target, i != j as a normal case.

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hash;
        vector<int> ans(2);
        for(int i = 0; i < nums.size(); ++i){
            auto it = hash.find(target - nums[i]);
            if(it != hash.end()){
                ans[0] = it->second;
                ans[1] = i;
                break;
            }else{
                hash[nums[i]] = i;
            }
        }
        return ans;
    }
};

Last updated