解法:抽掉的两个数字之和为2倍的平均数,那么判断一下2倍的平均数是不是整数。然后在搞一个哈希表存取过的值即可。
package com.sky;
import java.util.*;
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
while (T-- > 0) {
int n = scanner.nextInt();
long[] a = new long[n];
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = scanner.nextLong();
sum += a[i];
}
if (2 * sum % n != 0) {
System.out.println(0);
continue;
}
long target = 2 * sum / n;
Map<Long, Integer> countMap = new HashMap<>();
long result = 0;
for (int i = 0; i < n; i++) {
long complement = target - a[i];
if (countMap.containsKey(complement)) {
result += countMap.get(complement);
}
countMap.put(a[i], countMap.getOrDefault(a[i], 0) + 1);
}
System.out.println(result);
}
}
}