:: [intv] Find two elements in an array that add to X (uses Map) ::
HOME


[Date Prev][Date Next][Date Index]

[intv] Find two elements in an array that add to X (uses Map)


//Problem: Given an array of integers and a number X. //Find an two numbers which add up to X.
//Save as: main.cpp and compile as: g++ -o main main.cpp


#include <iostream>
#include <map>
using namespace std;
typedef map<int, int, less<int> > MAP;

void findElements(int *, int, int);

int main(){
  int a[6] = {2, 4, 3, 5, 6, 3};
  findElements(a, 6, 12);

}

void findElements(int *a, int aSize, int X){

  MAP theMap;
  MAP::iterator itr;

  for (int i=0; i < aSize; i++){
    if (a[i] < X){
      //check if the X-complement of the element is already in the set.
      itr = theMap.find(X-a[i]);
      if (itr == theMap.end()){
	//Complement not found. Insert (element, idx).
	theMap.insert(MAP::value_type(a[i], i));
      }else{
	//Complemet found. Print out the two number.
	cout << "Found (" << a[i] << "," << X-a[i] << ")" << endl;
	cout << "Idx (" << i << "," << (*itr).second << ")" << endl;
	return;
      }

    }
  }
  cout << "No elements found" << endl;
  return;
}


Comments and corrections are appreciated and can be sent to papers@mia.ece.uic.edu. Click here for ©opyright information.