Here is the link:- https://ide.codingblocks.com/s/451249, please complete the given function, I am getting difficulty because of the constraint of not using same element twice and please do it with hashmap.
Code Implementation
hello @Sakshi2004
this problem is already covered in ur course.
pls check target sum pair video of ur course , it is exaclty same problem
Target sum pair video might be covered in sorting using the pointer approach, I want to solve this using hashmap and also how to handle the duplicates part with answer to be returned is index in pair.
check this ->
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
int n = nums.size();
for(int i=0;i<n;i++)
m.insert({nums[i], i});
vector<int> ans;
for(int i=0;i<n;i++){
int check = target - nums[i];
if(m.find(check) != m.end()){
if(m[check] != i){
ans.push_back(i);
ans.push_back(m[check]);
break;
}
}
}
return ans;
}
in hash map we are storing i corresponding to each value.
and then we are iterating from i=0 to n-1 and checking whether target - nums[i] is present or not.
if it is present then we are making sure that it should not be present at index i
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.