Two Sum
array • hash-table
Easy
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Solution
Use a hash map to store value->index while iterating the array.
For each number, check if target - num exists in map; if yes, return the pair of indices.
This is time and space.
Two Sum
array • hash-table
Easy
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Solution
Use a hash map to store value->index while iterating the array.
For each number, check if target - num exists in map; if yes, return the pair of indices.
This is time and space.
Code Solution
two-sum.cpp
cpp
1#include <vector>2#include <unordered_map>3using namespace std;45vector<int> twoSum(vector<int>& nums, int target) {6unordered_map<int,int> map;7for (int i = 0; i < (int)nums.size(); ++i) {8int need = target - nums[i];9if (map.count(need)) return {map[need], i};10map[nums[i]] = i;11}12return {};13}