Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

 1 struct node{
 2     int val;
 3     int pos;
 4 };
 5 bool compare (node &a,node &b)
 6 {
 7     return a.val<b.val;
 8 }
 9 class Solution {
10 public:
11     vector<int> twoSum(vector<int>& nums, int target) {
12         node tnode[nums.size()];
13         for(int i=0;i<nums.size();i++)
14         {
15             tnode[i].val=nums[i];
16             tnode[i].pos=i+1;
17         }
18         sort(tnode,tnode+nums.size(),compare);
19         vector<int> res;
20         int start=0,end=nums.size()-1;
21         while(start<end)
22         {
23             if(tnode[start].val+tnode[end].val==target)
24                 {if(tnode[start].pos>tnode[end].pos)
25                 swap(tnode[start].pos,tnode[end].pos);
26                 res.push_back(tnode[start].pos);
27                 res.push_back(tnode[end].pos);
28                 return res;}
29             else if(tnode[start].val+tnode[end].val<target)
30             start++;
31             else end--;
32         }
33     }
34 };

 

 1    vector<int> twoSum(vector<int> &numbers, int target) {  
 2       map<int, int> mapping;  
 3       vector<int> result;  
 4       for(int i =0; i< numbers.size(); i++)  
 5       {  
 6           mapping[numbers[i]]=i;  
 7       }  
 8       for(int i =0; i< numbers.size(); i++)  
 9       {  
10           int searched = target - numbers[i];  
11           if(mapping.find(searched) != mapping.end())  
12           {  
13               result.push_back(i+1);  
14               result.push_back(mapping[searched]+1);  
15               break;  
16           }  
17       }  
18       return result;  
19 }