LeetCode Problem Explanations and Solutions (C++)
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. You may assume that each input would have exactly one solution, and you
may not use the same element twice.
Input/Output:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Explanation:
Approach:
- Use a hash map to store the complement (target - nums[i]) and index.
- As we iterate through the array, check if the current number exists in the hash map.
Time Complexity: O(n), Space Complexity: O(n)
C++ Code:
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashmap;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (hashmap.find(complement) != hashmap.end()) {
return {hashmap[complement], i};
hashmap[nums[i]] = i;
return {};
};