I was solving the question in leetcode.com. The question is 2sum. Link: 2sum question The following was the best solution provided by someone:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution{
public:
vector<int> twoSum(vector<int> &nums, int sum){
//write code here
int len = nums.size();
unordered_map<int, int> hashTable;
for(int i=0; i<len; i++){
int diff = sum - nums[i];
auto found = hashTable.find(diff);
if(found == hashTable.end()){
hashTable.insert(pair<int, int>{nums[i], i});
}
else{
return vector<int>{found->second, i};
}
}
}
};
int main()
{
vector<int> myArray;
vector<int> outputArray;
int sum,n,temp;
cout<<"enter the size of the array\n";
cin>>n;
cout<<"enter the integers\n";
for(int i=0; i<n; i++){
cin>>temp;
myArray.push_back(temp);
}
cout<<"enter the sum\n";
cin>>sum;
Solution s;
outputArray = s.twoSum(myArray, sum);
cout<<"["<<outputArray[0]<<","<<outputArray[1]<<"]"<<endl;
return 0;
}
In the above code, auto found = hashTable.find(diff);
how this line is working as the hashTable was never initialized. So, how it is finding the diff value. And then how the if condition is working? When I tried to print the contents of the hashTable using iterator, it returned empty value i.e., hashTable was empty. Then how it is finding the diff value? Please help me in understanding. Thanks for all the opinions.
Aucun commentaire:
Enregistrer un commentaire