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

后端 未结 30 999
暗喜
暗喜 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:56

    # Let arr be the given array.
    # And K be the give sum
    
    
    for i=0 to arr.length - 1 do
      # key is the element and value is its index.
      hash(arr[i]) = i  
    end-for
    
    for i=0 to arr.length - 1 do
      # if K-th element exists and it's different then we found a pair
      if hash(K - arr[i]) != i  
        print "pair i , hash(K - arr[i]) has sum K"
      end-if
    end-for
    

提交回复
热议问题