Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Last active August 16, 2020 01:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhaveshmunot1/c7f7e1b62b656f6b3cb995b4b0d3ad3d to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/c7f7e1b62b656f6b3cb995b4b0d3ad3d to your computer and use it in GitHub Desktop.
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