我一直在研究GeeksforGeeks上的一个排列问题。这是挑战的链接:http://www.practice.geeksforgeeks.org/problem-page.php?pid=702
挑战是取一个数字数组,对于这些数字在2或3组中的每一个可能的顺序,检查这些数字的总和是否能被3整除。在程序结束时,打印出能被3整除的组的个数。
一个例子是…Int [] array ={1,2,3}应该输出8。
下面是我用于这个挑战的代码。代码可以工作,但是太慢了。运行时需要低于1.272秒,所以我怎么能使这段代码更快?或者避免执行这么多行?
public static void PG2(int[] array, int l, int r, Counter count){
int newR = r - 1;
int i;
if(l == 2){
String number = String.valueOf(array[0]);
String number2 = String.valueOf(array[1]);
number = number.concat(number2);
int aNumber = Integer.parseInt(number);
count.divBy3(aNumber);
} else {
int temp;
int temp2;
for(i = l; i < r; i++){
temp = array[l];
array[l] = array[i];
array[i] = temp;
PG2(array, l+1, r, count);
temp2 = array[l];
array[l] = array[i];
array[i] = temp2;
}
}
}
public static void PG3(int[] array, int l, int r, Counter count){
int newR = r - 1;
int i;
if(l == 3){
String number = String.valueOf(array[0]);
String number2 = String.valueOf(array[1]);
String number3 = String.valueOf(array[2]);
number = number.concat(number2);
number = number.concat(number3);
int aNumber = Integer.parseInt(number);
count.divBy3(aNumber);
} else {
int temp;
int temp2;
for(i = l; i < r; i++){
temp = array[l];
array[l] = array[i];
array[i] = temp;
PG3(array, l+1, r, count);
temp2 = array[l];
array[l] = array[i];
array[i] = temp2;
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String t = input.readLine();
int T = Integer.parseInt(t);
while(T > 0){
String arrayS = input.readLine();
int ArrayS = Integer.parseInt(arrayS);
int[] newArray = new int[ArrayS];
String arrayElements = input.readLine();
String[] ArrayElements = arrayElements.trim().split("\s+");
for(int i = 0; i < ArrayS; i++){
int num = Integer.parseInt(ArrayElements[i]);
newArray[i] = num;
}
int total = 0;
Counter count = new Counter();
PG2(newArray, 0, ArrayS, count);
PG3(newArray, 0, ArrayS, count);
System.out.println(count.counter);
T--;
}
}
这是计数器类:
public class Counter {
public int counter;
public void divBy3(int number){
int total = 0;
while(number > 0){
total += number % 10;
number = number / 10;
}
if(total % 3 == 0){
this.counter++;
}
}
}
你的代码创建了很多不必要的对象。
首先,不需要计数器类,您可以很容易地保留一个int计数器,表示符合要求的组的数量。
当计算一个和是否能被3整除时,你不需要通过数字,只需检查(对于int n
): if (n % 3 == 0) { ...
你正在创建字符串,然后不必要地将整型转换为字符串,然后再转换回来。只需将命令行中的int值读入int数组并使用它即可。
// a main method that reads in ints and then keeps them as such
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t > 0) {
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
int count = countGroupsOfTwo(arr);
count += countGroupsOfThree(arr);
System.out.println(count);
t--;
}
最后,递归将比简单的for循环迭代慢。我个人也不认为递归使解决方案更简洁。
我根据这些建议快速拼凑了一个简单的解决方案,只花了半秒就运行了。