Two Sum

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

C++:
01 class Solution {
02 public:
03     vector<int> twoSum(vector<int> &numbers, int target) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         map<int, int> A;
07         vector<int> result;
08         for(int i=0;i<numbers.size();i++)
09         {
10             int t=numbers[i];
11             int k=targett;
12             if(A.find(k)==A.end())
13             {
14                 A[t]=i;
15             }
16             else
17             {
18                 result.push_back(A[k]+1);
19                 result.push_back(i+1);
20                 return result;
21             }
22         }
23     }
24 };
Advertisements
This entry was posted in Array and linked list, Hashtable and Map. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s