Find a pair of elements from an array whose sum equals a given number

后端 未结 30 1494
暗喜
暗喜 2020-11-22 10:14

Given array of n integers and given a number X, find all the unique pairs of elements (a,b), whose summation is equal to X.

The following is my solution, it is O(nLo

30条回答
  •  再見小時候
    2020-11-22 10:59

    Nice solution from Codeaddict. I took the liberty of implementing a version of it in Ruby:

    def find_sum(arr,sum)
     result ={}
     h = Hash[arr.map {|i| [i,i]}]
     arr.each { |l| result[l] = sum-l  if h[sum-l] && !result[sum-l]  }
     result
    end
    

    To allow duplicate pairs (1,5), (5,1) we just have to remove the && !result[sum-l] instruction

提交回复
热议问题