Two Sum : of Array Element thats equal to target sume

Save the index of an element to a hashmap that if deduction from target is not equal to already substracted element.

class Solution {

public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> imap(nums.size()); for( int i=0; i<nums.size(); ++i) { if(imap.find(target-nums[i]) == imap.end()) { imap[nums[i]] = i; } else return {imap[target-nums[i]], i}; } return {0,0}; } };

Comments

Popular posts from this blog

From Zero to Production-Ready: Your Year-Long Journey to Mastering System Design

LinkedList: Add Two Numbers - C++