Java Оптимизация кода
Нужно оптимизировать этот код для олимпиады, т.к. превышен лимит времени выполнения. (лимит - 3s, пишет, что выполняется за ~3.050 s
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
final Scanner scanner = new Scanner(new File("input.txt"));
final Stream<String> x = Files.lines(Paths.get("input.txt"));
final int num = Integer.parseInt(scanner.next());
int lines = -1;
int[] connections = new int[num];
while(scanner.hasNextLine()) {lines++;}
for (int a = 1; a < lines; a++) {
Scanner scan = new Scanner(x.skip(a).findFirst().get());
connections[Integer.parseInt(scan.next())]++;
connections[Integer.parseInt(scan.next())]++;
}
int first = 0,second = 0;
for (int t : connections) {
if (t > first) {
second = first;
first = t;
}
}
System.out.print(first + " " + second);
}
}
Ответы (1 шт):
Автор решения: JEasily Course
→ Ссылка
Попробуйте заменить это:
while(scanner.hasNextLine()) {lines++;}
for (int a = 1; a < lines; a++) {
Scanner scan = new Scanner(x.skip(a).findFirst().get());
connections[Integer.parseInt(scan.next())]++;
connections[Integer.parseInt(scan.next())]++;
}
на код ниже:
int lines = 1;
while(scanner.hasNextLine()) {
Scanner scan = new Scanner(x.skip(lines).findFirst().get());
connections[Integer.parseInt(scan.next())]++;
connections[Integer.parseInt(scan.next())]++;
lines++;
}
Рекомендуем вам ознакомиться с нашим курсом на сайте JEasily Course