Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 28 additions & 15 deletions Leetcode/1._Two_Sum.cpp
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
//1. Two Sum Leetcode Solution
// Two Sum LeetCode Solution

#include <vector>
#include <unordered_map>

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash;
vector<int> ans;
for(int i = 0;i<nums.size();i++)
if(hash.count(target-nums[i])>0)
{
ans.push_back(hash[target-nums[i]]);
ans.push_back(i);
return ans;
}
else
hash[nums[i]] = i;
return ans;
std::vector<int> twoSum(std::vector<int>& nums, int target) {
std::unordered_map<int, int> hash_map;
std::vector<int> result;

// Iterate through the array
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];

// Check if the complement is in the hash map
auto it = hash_map.find(complement);
if (it != hash_map.end()) {
// Found a pair that sums to the target
result.push_back(it->second);
result.push_back(i);
return result;
}

// Store the current number and its index in the hash map
hash_map[nums[i]] = i;
}

return result; // Return an empty vector if no solution is found
}
};
};