Two-sum solution

This commit is contained in:
2025-12-06 10:00:23 +00:00
parent de106b2e33
commit 6363aeaed3
4 changed files with 57 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
class Solution{
public:
vector<int> twoSum(vector<int> &nums, int target) {
unordered_map<int, int> hash;
for (int i = 0; i < nums.size(); i++) {
hash[nums[i]] = i;
}
for (int i = 0; i < nums.size(); i++) {
int comp = target - nums[i];
if (hash.find(comp) != hash.end() && hash[comp] != i) {
return {i, hash[comp]};
}
}
return {};
}
};
+13
View File
@@ -0,0 +1,13 @@
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i=0;i<nums.size();i++)
{
for(int j=i+1;j<nums.size();j++)
if(nums[i]+nums[j] == target)
return {i,j};
}
return {};
}
};
+15
View File
@@ -0,0 +1,15 @@
One pass:
one pass starts from index 0 and stores it in a map,
and for next number in array,
it computes the new complement and checks if its present in map,
if yes then prints
else stores the original number in hash and continues
Two pass:
Two-pass hash table solution first builds a map of all values to their indices,
then makes a second scan through the array to compute each elements complement
and check if it exists in the map.
+13
View File
@@ -0,0 +1,13 @@
public:
vector<int> twoSum(vector<int>& nums, int target){
unordered_map<int,int>hash;
for(int i=0;i<nums.size();++i){
int comp = target - nums[i];
if(hash.find(complement) != hash.end(){
return {hash[complement],i};
hash[nums[i]] = i;
}
}
}