for循环两个分号之间不要乱加判断条件(记洛谷P2141题WA的经历)
程序员文章站
2024-03-17 20:56:34
...
题目要求
分析
暴力法可解——我们只需遍历一遍数组,在里面再遍历一次,再遍历一次,共三层嵌套,需要保证内层counter数值不能与外面诸层的counter相同~~
暴力还可防漏,很划算的呀~~
第一次提交——WA
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int[] array = new int[num];
for (int i = 0; i < num; i++) {
array[i] = scanner.nextInt();
}
int counter = 0;
for (int i = 0; i < num; i++) {
int now = array[i];
for (int j = 0; j < num && j != i; j++) {
int num1 = array[j];
for (int k = 0; k < num && k != i && k != j; k++) {
int num2 = array[k];
if (num1 + num2 == now) {
counter++;
}
}
}
}
System.out.println(counter);
scanner.close();
}
}
我傻了,但必须冷静分析,问题在哪里啊?
问题分析:
我们开一组新的测试用例(自编):
然后我们打开Debug重新看程序运行的流程,发现这是不对的:
如果我们把判断条件放在for循环两个;的中间,则一旦失败就不会继续执行,所以这个条件必须放在for的内部~~
第二次提交——AC
放出AC代码(Java语言描述):
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int[] array = new int[num];
for (int i = 0; i < num; i++) {
array[i] = scanner.nextInt();
}
int[] counterArr = new int[num];
for (int i = 0; i < num; i++) {
int now = array[i];
for (int j = 0; j < num; j++) {
if (j == i) {
continue;
}
int num1 = array[j];
for (int k = 0; k < num; k++) {
if (k == i || k == j) {
continue;
}
int num2 = array[k];
if (num1 + num2 == now) {
counterArr[i] = 1;
break;
}
}
}
}
int counter = 0;
for (int i = 0; i < num; i++) {
if (counterArr[i] == 1) {
counter++;
}
}
System.out.println(counter);
scanner.close();
}
}