From caa2053b45f16278f11ce97889aa57544ea1f94c Mon Sep 17 00:00:00 2001 From: Jyoti Pandey <91590380+jyotip31@users.noreply.github.com> Date: Tue, 10 Oct 2023 21:31:23 +0530 Subject: [PATCH] Update 1._Two_Sum.cpp 1. Added comments to explain the code logic. 2. Used a consistent naming convention and improved variable names for better readability. 3. Moved #include statements to the top of the code for clarity. 4. Adjusted indentation and formatting to follow a standard coding style. --- Leetcode/1._Two_Sum.cpp | 43 +++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 15 deletions(-) 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 +};