Ich habe folgendes Programm. In einem Fall, wo es mehrere Funktionen hat, kombiniere ich die Zeitkomplexität von jedem oder nehme nur die höchste Zeitkomplexität von allen von ihnen?Java: Wie berechnet man die zeitliche Komplexität eines Programms?
Ich glaube, die find()
hat eine Zeit Komplexität von n und isCompound
hat eine Zeit Komplexität von n hat gut. Ist das korrekt?
Vielen Dank und werde sicher sein, zu stimmen und die Antwort zu akzeptieren.
private static String[] find(String[] array) {
Set<String> words = new LinkedHashSet<>(Arrays.asList(array));
Set<String> otherWords = new HashSet<>(words);
for (Iterator<String> i = words.iterator(); i.hasNext();) {
String next = i.next();
otherWords.remove(next);
if (isCompound(next, otherWords)) {
i.remove();
} else {
otherWords.add(next);
}
}
}
private static boolean isCompound(String string, Set<String> otherWords) {
if (otherWords.contains(string)) {
return true;
}
for (String word : otherWords) {
if (string.startsWith(word)) {
return isCompound(string.replaceAll("^" + word, ""), otherWords);
}
if (string.endsWith(word)) {
return isCompound(string.replaceAll(word + "$", ""), otherWords);
}
}
return false;
}
Es hängt davon ab, wie die Funktionen interagieren. – bradimus
Loops wie in 'for loops' in Ihrem Programm hätten eine 'lineare Zeitkomplexität' dh' O (n) 'und wenn die Folge 'O (1)' wäre – CodeWalker
Bitte beachten Sie, dass Sie hier zwei Variablen haben: die Anzahl der Wörter und die Länge jedes Wortes. Denken Sie darüber nach, was beispielsweise passiert, wenn Ihre Arrays nur ein einziges Wort enthalten, das aus einer Milliarde Zeichen besteht. Ihr begrenzender Faktor wird in diesem Fall definitiv nicht die Anzahl der Wörter sein. – biziclop