algorithm - Find three indices x, y, z such that M[x] + M[y] = N[z] -
algorithm - Find three indices x, y, z such that M[x] + M[y] = N[z] -
given 2 array (not sorted) m , n. have find 3 index x, y (in m) , z (in n) such m[x] + m[y] = n[z]. initial algorithm takes o(m *m *n) solution. please note, have find indexes , sorting alter indexes.
o(m *m *n) pseudo code (where m , n length of respective array):
for(int = 0; < m - 1; i++) for(int j = + 1; j < m; j++) for(int k = 0; k < n; k++) if(m[i] + m[j] == n[k] { print i, j, k }
i'm looking more optimized solution.
thanks.
insert m
hash array (hash set / hash table) have o(1)
contains check. iterate on items in n
, within loop iterate on hash set, pseudocode:
foreach(integer x in n) foreach(integer sety in hasharray) if ( hasharray.contains( x - sety ) ) solution is: sety + (x-sety) = x;
you can find these items indexes in linear time. overall running time o(|n|*|m|)
. maintain in mind might need handle corner cases (like x = 2*sety).
algorithm sorting
Comments
Post a Comment