If you have a limit on the maximum possible number (let's name it M) then you can have a solution in O(M+n).
Boolean array of false and mark as true all value for element of A. Then for each element b of B check if the element number K-b is marked as true.
You can improve it if you are using an hash-map instead of a big array. But I would consider that in this kind of questions hash-map is kind of cheating.
Anyway if would give you O(n) for insertion and then O(n) for query, O(n) in total.
EDIT :
One case where this might be useful.
- You have un-sorted vectors of size 10^6, so sorting them and doing the match is in O(n log n) with n = 10^6.
- You need to do this operation 10^6 times (different vectors), complexity of O(n*n*log n).
- Maximum value is 10^9.
Using my idea with not with boolean but integer (incremented at each run) gives you a complexity of :
- "O(10^9)" to create the array (also same complexity of space)
- O(n) at each run, so O(n*n) for the total.
You are using more space but you've increased speed by a factor log(n) ~=20 in this case !