Subject description:
Given an array, to find out whether there are two pairs of array (a, b), and (C, d), such that a + b = c + d, wherein a, b, c and d are different elements. If there are multiple answers, print any one can be. For example given array [3,4,7,10,20,9,8], you can be found in a number of two (3,8) and (4,7), such that 3 + 4 + 8 = 7.
Ideas:
The easiest way is to quadruple traverse of all possible pairs of determining whether to meet the requirements, if the print out, time complexity of this method is O (n ** 4);
are presented dictionary method: logarithm traversing unit, during traversal, the sum of the present value of the number of dictionaries ( 键为数对的和,值为数对
key), when traversing to a key-value pair, and if it already exists in the dictionary, then meet the conditions found value pairs.
Performance Analysis:
time complexity of O (n ** 2), because of the use of the double loop, the actual time of insertion of the dictionary lookup operation complexity is O (1);
Code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/1/22 19:31
# @Author : buu
# @Software: PyCharm
# @Blog :https://blog.csdn.net/weixin_44321080
class Pair:
def __init__(self, first, second):
self.first = first
self.second = second
def findPairs(arr):
sumPair = dict() # 键为数对的和,值为数对
n = len(arr)
i = 0
while i < n: # 遍历数组中所有可能的数对
j = i + 1
while j < n:
sums = arr[i] + arr[j]
if sums not in sumPair.keys(): # 若数对的和在字典的键中不存在,在加入
sumPair[sums] = Pair(arr[i], arr[j])
else: # 若数对的和存在字典的键中,则满足要求,打印出来即可
p = sumPair[sums]
print('(' + str(p.first) + ',' + str(p.second) \
+ ')', '(' + str(arr[i]) + ',' + str(arr[j]) + ')')
return True
j += 1
i += 1
return False
if __name__ == '__main__':
arr = [3, 4, 7, 10, 20, 9, 8]
findPairs(arr)
The results:
End