Answer the question
In order to leave comments, you need to log in
How can this program be optimized?
Hello. I have a program like this, but it runs too slowly. I have a limit of 1 sec and 256 MiB. But my program runs in 1.015 seconds. How can you speed it up? Perhaps there is something that immediately
catches the eye.
package mariaAndSweets;
import java.util.Collections;
import java.util.LinkedList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
final class Main {
static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
final int number = scanner.nextInt(), min = scanner.nextInt();
LinkedList<Integer> sweets = new LinkedList<>();
LinkedList<Integer> copy = new LinkedList<>();
for (int i = 0; i < number; i++)
sweets.add(scanner.nextInt());
scanner.close();
Set<Integer> set = new HashSet<>(sweets);
copy.addAll(set);
for (int i = 0; i < copy.size(); i++) {
if (Collections.frequency(sweets, copy.get(i)) >= min) {
Collections.sort(sweets);
StringBuilder sb = new StringBuilder();
for (Integer j : sweets)
sb.append(j + " ");
System.out.print(sb);
return;
}
}
System.out.print("Oh sh*t");
}
}
Answer the question
In order to leave comments, you need to log in
she won't accept the gift if there are no k consecutive candies of the same type
Maybe it will be faster?
LinkedList<Integer> sweets = new LinkedList<>();
StringBuilder sb = new StringBuilder();
AtomicBoolean hasMinAmount = new AtomicBoolean(false);
sweets.stream()
.collect(Collectors.toMap(Integer::intValue, integer -> 1, Math::addExact))
.forEach((candyName, amount) -> {
if (amount >= min) {
hasMinAmount.set(true);
}
for (int i = 0; i < amount; i++) {
sb.append(candyName + " ");
}
});
if (hasMinAmount.get()) {
System.out.print(sb);
} else {
System.out.println("Oh sh*t");
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question