我从 HackerEarth解决了以下问题。所有测试用例都是正确的,除了最后一个因为它超时了。我尝试优化我的解决方案,但我无法更好地优化它。这是我的解决方案:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
class TestClass {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
Set<Integer> perfectNumbers = new HashSet<>();
for (int i = 0; i <= 20; i++) {
perfectNumbers.add(i * i * i);
}
for (int i = 1; i <= 44; i++) {
perfectNumbers.add(i * i);
}
int t = sc.nextInt();
for (int k = 0; k < t; k++) {
int db = 0;
int n = sc.nextInt();
int[] a = new int[1001];
int[] b = new int[1001];
int[] numbers = new int[n];
for (int j = 0; j < n; j++) {
int x = sc.nextInt();
numbers[j] = x;
for (Integer perfect : perfectNumbers) {
if (x == perfect - x) {
b[x]++;
} else if (perfect - x >= 0 && perfect - x <= 1000)
a[perfect - x]++;
}
}
for (int j = 0; j < n; j++) {
db += a[numbers[j]];
}
for (int j = 0; j <= 1000; j++) {
if (b[j] > 1) {
db += b[j] * (b[j] - 1);
}
}
System.out.println(db / 2);
}
}
}
相关分类