Leetcode_easy_twosum

2021/04/17

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Solution

brute-force

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for(int i=0; i < nums.size(); ++i)
        {
            int left = target - nums[i];
            for(int j=i+1; j < nums.size(); j++)
            {
                if(nums[j] == left)
                {
                    return {i, j};
                }
            }
        }

        return {};
    }
};

hashmap

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> indices;
        for(int i=0; i < nums.size(); ++i )
        {
            indices[nums[i]] = i;
        }

        for(int i=0; i < nums.size(); ++i)
        {
            int left = target - nums[i];
            if(indices.count(left) && indices[left] != i)
            {
                return {i, indices[left]};
            }
        }

        return {};
    }
}

Comments🎉