Quick Solutions for the 2Sum Problem on Leetcode

JavaJava
1 min read

The Problem:

Given an array of integers, nums and a target integer, the task is to find the indices of two numbers in nums that add up to target. We are to assume there's always one unique solution, and we can't use the same element twice. The order of the returned indices doesn't matter.

The Solution:

From what I can understand, using hash map to store the indices would be the only viable solution.

Using Hash Map

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n = size(nums);
        unordered_map<int, int> hash;
        for (int i =0; i < n; ++i) {
            int comp = target-nums[i];
            if (hash.find(comp) != hash.end()) { // so that it does not return anything if the it
// reaches the end
                return {hash[comp], i};
            }
            hash[nums[i]] = i; // updating the hash table
        }
        return {};
    }
};

The same concept for 3sum [get funny whenever i say it out loud].

thank you

0
Subscribe to my newsletter

Read articles from Java directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Java
Java