Buongiorno a tutti!
Sto provando a risolvere il problema trending e penso di aver capito logicamente come risolverlo, ma con le strutture che sto usando vado in TLE.
Ecco il mio codice che per ora passa i primi tre subtask.
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
public class trending {
record Hashtag(String name, int occurrences) {
}
// Comparatore personalizzato per ordinare in base ai valori e alle chiavi
static class HashtagComparator implements Comparator<Hashtag> {
@Override
public int compare(Hashtag o1, Hashtag o2) {
if (o2.occurrences == o1.occurrences) {
return String.CASE_INSENSITIVE_ORDER.compare(o1.name, o2.name);
} else {
return Integer.compare(o2.occurrences, o1.occurrences);
}
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
int N = in.readInt();
int T = in.readInt();
String[] hashtagsName = new String[N];
for (int i = 0; i < N; i++) {
hashtagsName[i] = in.readString();
}
for (int i = 0; i + T - 1 < N; i++) {
HashMap<String, Integer> trendingMap = new HashMap<>();
for (int j = 0; j < T; j++) {
String hashtag = hashtagsName[i + j];
if (!trendingMap.containsKey(hashtag)) {
trendingMap.put(hashtag, 1);
} else {
trendingMap.put(hashtag, trendingMap.get(hashtag) + 1);
}
}
Hashtag[] hashtags = new Hashtag[trendingMap.size()];
int index = 0;
for (HashMap.Entry<String, Integer> entry : trendingMap.entrySet()) {
hashtags[index++] = new Hashtag(entry.getKey(), entry.getValue());
}
Arrays.sort(hashtags, new HashtagComparator());
System.out.println(hashtags[0].name);
}
}
}
Penso che la parte più lenta sia copiare i valori dalla mappa all’array e poi ordinarlo.
Avevo in mente di provare ad usare una sorted map, ma così potrei ordinare solo le chiavi, non anche i valori?
Qualche tip?