c++ - Find two elements in an array that sum to k -


possible duplicate:
given 2 arrays , b .find pairs of elements (a1,b1) such a1 belongs array , b1 belongs array b sum a1+b1 = k .

given : unsorted array a of integers
input : integer k

output : 2 element set sum of elements in each set equal k in o(n).

example:

a = {3,4,5,1,4,2}

input : 6
output : {3,3}, {5,1}, {4,2}

note : know o(n logn) solution require have array sorted. there way problem can solved in o(n). non-trivial c++ data structure can used i.e there's no bound on space

make constant-time lookup table (hash) can see if particular integer included in array (o(n)). then, each element in array, see if k-a[i] included. takes constant time each element, total of o(n) time. assumes elements distinct; not difficult make work repeating elements.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -