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

后端 未结 30 1095
暗喜
暗喜 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 11:02

    A simple python version of the code that find a pair sum of zero and can be modify to find k:

    def sumToK(lst):
        k = 0  # <- define the k here
        d = {} # build a dictionary 
    
    # build the hashmap key = val of lst, value = i
    for index, val in enumerate(lst):
        d[val] = index
    
    # find the key; if a key is in the dict, and not the same index as the current key
    for i, val in enumerate(lst):
        if (k-val) in d and d[k-val] != i:
            return True
    
    return False
    

    The run time complexity of the function is O(n) and Space: O(n) as well.

提交回复
热议问题