Last active
August 16, 2020 01:42
-
-
Save bhaveshmunot1/c7f7e1b62b656f6b3cb995b4b0d3ad3d to your computer and use it in GitHub Desktop.
Leetcode 1. Two Sum (https://www.InterviewRecipes.com/leetcode-1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> twoSum(vector<int>& nums, int target) { | |
unordered_map<int, int> m; // To store the integer and its index. | |
int n = nums.size(); // Total integers. | |
for (int i=0; i<n; i++) { // For each integer, say K - | |
if (m.find(target-nums[i]) != m.end()) { // Check if (target - K) exists. | |
return {i, m[target-nums[i]]}; // Yay, found the answer. | |
} | |
m[nums[i]] = i; // Save the K in the map with it's index. | |
} | |
return {}; // If the answer does not exists. | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment