Pair Sum

/***
17.12 Design an algorithm to find all pairs of integers within an array which sum to a specified value.
***/

#include<iostream>
#include<map>
#include<vector>

using namespace std;

vector<vector<int>> pairofgivenSum(int *a, int sz, int sum) {
       map<int, int> mymap;
       map<int, int> :: iterator it;
       vector<vector<int>> pairs;

       for(int i = 0; i < sz; i++) {
              it = mymap.find(sum - a[i]);
              if(it != mymap.end()) {
                     vector<int> v;
                     v.push_back(it->second);
                     v.push_back(it->first);
                     pairs.push_back(v);
                     mymap.erase(it);
              } else {
                     mymap.insert(pair<int, int>(sum-a[i], a[i]));
              }            
       }
       return pairs;

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs