【发布时间】:2015-03-07 00:43:34
【问题描述】:
我正在做一个有竞争力的编程问题,给你一个数字数组,然后是一定数量的查询。对于每个查询,您将获得 2 个整数,“a”和“b”。所以你应该输出数组中剩余元素的 GCD(不包括 a、b 以及它们之间的所有元素)。
例如,如果数组是:16,8,24,15,20,并且有 2 个查询 (2, 3) 和 (1, 3),则输出 1 为:1,输出 2 为:5。 请注意,索引是基于 1 的。
这是我的代码,我在其中实现了基本思想,其中包含一个用于查找传递给它的数组的 GCD 的函数。
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t-- > 0) { //This is the number of test cases
String[] s1 = br.readLine().split(" ");
int n = Integer.parseInt(s1[0]); //Number of elements in array
int q = Integer.parseInt(s1[1]); //Number of queries
String[] s2 = br.readLine().split(" ");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(s2[i]);
}
for (int i = 0; i < q; i++) { //for each query
String[] s3 = br.readLine().split(" ");
int a = Integer.parseInt(s3[0]) - 1;
int b = Integer.parseInt(s3[1]) - 1;
int[] copy = new int[n - b + a - 1]; //this is so that the original array doesn't get messed up
int index = 0;
for (int j = 0; j < n; j++) { //filing the array without the elements of the query
if (j < a || j > b) {
copy[index] = arr[j];
index++;
}
}
int fin = gcd(copy);
System.out.println(fin);
}
}
}
private static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
private static int gcd(int[] input) { //simple GCD calculator using the fact that GCD(a,b,c) === GCD((a,b),c)
int result = input[0];
for (int i = 1; i < input.length; i++)
result = gcd(result, input[i]);
return result;
}
问题是我在某些部件上获得了 AC(十分之六),而在其余部分上获得了 TLE。有人可以提出更好的方法来解决这个问题,因为我的方法似乎太慢了,几乎不可能进一步优化?
【问题讨论】:
-
对不起,我不明白你的例子是如何得到这些值的。对我来说
gcd(16,15,20) = 1和gcd(8,15,20) = 1。 -
@GáborBakos 真的很抱歉,我搞砸了。已更正。另外,我没有在那里提到 1 个关键点。请再次检查第一段。
-
GCD of an array的可能重复
-
@ILoveCoding 你的回答没有提供正确的解决方案(即使它被标记为如此),所以我想问另一个问题。
-
@pkm 它确实提供了正确的解决方案。是什么让您认为这是错误的?
标签: java performance algorithm