Given two arrays a and b .Find all pairs of elements (a1,b1) such that a1 belongs to Array A and b1 belongs to Array B whose sum a1+b1 = k

前端 未结 5 687
夕颜
夕颜 2020-11-27 16:25

I am looking for the solution of following algorithm with minimal time and space complexity.

Given two arrays a and b, find all pairs of elements (a1,

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 16:43

    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 not consider that in this kind of questions hash-map is kind of cheating.

    Anyway it 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 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 !

提交回复
热议问题