LeetCode Solutions (C++): First 75 Problems
1. Two Sum
Description
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Input/Output
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation
Use a hash map to store numbers and their indices as you iterate through the array. Check if the complement exists in
the map.
Solution (C++)
#include <unordered_map>
#include <vector>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); ++i) {
int complement = target - nums[i];
if (map.find(complement) != map.end()) {
return {map[complement], i};
map[nums[i]] = i;
return {};
Page 1