mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
Two-sum solution
This commit is contained in:
@@ -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 {};
|
||||
}
|
||||
};
|
||||
@@ -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 {};
|
||||
}
|
||||
|
||||
};
|
||||
@@ -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 it’s 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 element’s complement
|
||||
and check if it exists in the map.
|
||||
|
||||
@@ -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;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user