Yes, you can.
Your algorithm is running in O(n*m)
time, and is basically saying:
Are the two lists denoted as
A
andB
have any common items?
This can be done more efficiently if you first store one list into a set, which is implemented with more efficient data structure (Usually self balancing binary tree or hash table).
Then, you simply iterate the second list and check for matches.
Pseudo code:
Algorithm foo(A,n,B,m)
Input: arrays of integers, A of length n and B of length m
Output: true or false
s = new Hash/Tree set
for i := 0 to n
s.add(A[i])
endfor
for j := 0 to m
if s.contains(B[j])
return true
endif
endfor
return false
The new version will run in O(logn*(n+m))
or O(n+m)
, depending if you used tree based set or hash based set.
2
solved How would you change this to a while loop and make it have a better run-time complexity?