diff --git a/Leetcode/1._Two_Sum.cpp b/Leetcode/1._Two_Sum.cpp index b080f25b..94d6a8d7 100644 --- a/Leetcode/1._Two_Sum.cpp +++ b/Leetcode/1._Two_Sum.cpp @@ -1,18 +1,31 @@ -//1. Two Sum Leetcode Solution +// Two Sum LeetCode Solution + +#include +#include + class Solution { public: - vector twoSum(vector& nums, int target) { - unordered_map hash; - vector ans; - for(int i = 0;i0) - { - ans.push_back(hash[target-nums[i]]); - ans.push_back(i); - return ans; - } - else - hash[nums[i]] = i; - return ans; + std::vector twoSum(std::vector& nums, int target) { + std::unordered_map hash_map; + std::vector 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 } -}; \ No newline at end of file +};