## Monday, March 4, 2013

### [LeetCode] Two Sum, Solution

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
» Solve this problem

[Thoughts]

``````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:    }
``````

``````1:       struct Node
2:       {
3:            int val;
4:            int index;
5:            Node(int pVal, int pIndex):val(pVal), index(pIndex){}
6:       };
7:       static bool compare(const Node &left, const Node &right)
8:       {
9:            return left.val < right.val;
10:       }
11:       vector<int> twoSum(vector<int> &numbers, int target) {
12:            vector<Node> elements;
13:            for(int i =0; i< numbers.size(); i++)
14:            {
15:                 elements.push_back(Node(numbers[i], i));
16:            }
17:            std::sort(elements.begin(), elements.end(), compare);
18:            int start = 0, end = numbers.size()-1;
19:            vector<int> result;
20:            while(start < end)
21:            {
22:                 int sum = elements[start].val + elements[end].val;
23:                 if(sum == target)
24:                 {
25:                      result.push_back(elements[start].index+1);
26:                      if(elements[start].index < elements[end].index)
27:                           result.push_back(elements[end].index+1);
28:                      else
29:                           result.insert(result.begin(),elements[end].index+1);
30:                      break;
31:                 }
32:                 else if(sum > target)
33:                      end--;
34:                 else
35:                      start++;
36:            }
37:            return result;
38:       }
``````