checking if 2 numbers of array add up to I

后端 未结 15 2615
日久生厌
日久生厌 2020-12-15 01:13

I saw a interview question as follows: Give an unsorted array of integers A and and an integer I, find out if any two members of A add up to I.

any clues?

ti

15条回答
  •  离开以前
    2020-12-15 01:41

    An implementation in python

    def func(list,k):
    temp={} ## temporary dictionary
    for i in range(len(list)):
        if(list[i] in temp): ## if temp already has the key just increment its value
            temp[list[i]] +=1
        else:  ## else initialize the key in temp with count as 0
            temp[list[i]]=0 
    
        if(k-list[i] in temp and ((k/2 != list[i]) or temp[list[i]]>=1)): ## if the corresponding other value to make the sum k is in the dictionary and its either not k/2 or the count for that number is more than 1
            return True
    
    return False
    

    Input: list is a list of numbers (A in the question above)...
    k is the sum (I in the question above)....

    The function outputs True if there exist a pair in the list whose sum is equal to k and False otherwise...

    I am using a dictionary whose key is the element in the array(list) and value is the count of that element(number of times that element is present in that list). Average running time complexity is O(n).

    This implementation also takes care of two important edge cases:

    • repeated numbers in the list and
    • not adding the same number twice.

提交回复
热议问题