我想在数组中找到对的最大GCD示例:2,4,7,9,14,15输出:7
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
int result = findMaxGCD(nums);
System.out.println(result);
}
public static int findMaxGCD(int[] arr) {
int maxGCD = 0;
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int gcd = gcd(arr[i], arr[j]);
if (gcd > maxGCD) {
maxGCD = gcd;
}
}
}
return maxGCD;
}
public static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
}
我测试我的解决方案,但它有一个运行时的问题,它是超时。你能帮我保存更多的时间吗?
最好的解决方案。它有一个运行时的问题,它是超时。你能帮我保存更多的时间。
1条答案
按热度按时间hpcdzsge1#
首先,你打开一个scanner对象,读取一个数字,然后打印结果,但是你必须在最后关闭scanner对象。
在读取输入后添加sc.close()