固定和的元素对
题目描述
Description
输入一个数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字,统计这样两个数的对数。
Input
输入第一行为用例个数, 每个测试用例输入第一行是数组,每一个数用空格隔开;第二行是数字和。
Output
输出这样两个数有几对。
Sample Input 1
1
1 2 4 7 11 0 9 15
11
Sample Output 1
3
思路解析:
就是类似于求两数和的思想leetcode 两数和,只不过那个数输出符合条件的两个数,这个是统计满足结果的数量,这里可以使用map达到时间复杂度为O(n)
- 遍历数组,将目标和与当前数的差作为key,
- 若遍历到某个数时,map中有该key,则count++
代码实现(python)
时间复杂度O(n)
if __name__ == '__main__':
for _ in range(int(input())):
# arr = [1, 2, 4, 7, 11, 0, 9, 15]
arr = map(int, input().split())
num = int(input())
dic = {}
count = 0
for x in arr:
if x in dic.keys():
count += 1
else:
dif = num - x
dic[dif] = x
print(count)
8万+

被折叠的 条评论
为什么被折叠?



