F5 Interview Question

Given an array & a value x, find if the array contains any 2 values whoes sum = x

Interview Answers

Anonymous

Jan 22, 2014

#include #include using namespace std; bool findIfSum(const vector &x, const int val) { vectory = x; sort(begin(y), end(y)); for (auto i = y.begin(); i != y.end(); ++i) { int diff = val - *i; if (diff < 0) return false; if (binary_search (i, y.end(), diff)) return true; } return false; }

2

Anonymous

Aug 29, 2012

def has_sum( l, v ): # assuming more than 2 elements for i in range( len(l) ): _v = v - l[i] _l = l[0:i] + l[i+1:] if _v in _l : return True return False

2