0% found this document useful (0 votes)
624 views2 pages

LeetCode Solutions C++ All Boxed

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
624 views2 pages

LeetCode Solutions C++ All Boxed

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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 {};

};

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy