这个算法的时间复杂度是多少?
我知道 array.map 的复杂度为 O(n),其中 n 是数组的长度。我还读到 string.slice() 的时间复杂度也为 O(n)。但是,由于 slice 取决于单词的长度,我说时间复杂度为 0(n + m) 是否正确,其中 m 是单词的长度。
function sentenceCaps(str) {
if (!str) {
return new Error('empty string');
}
let arr = str.toLowerCase().split(' ');
let results = arr.map(word => {return word[0].toUpperCase()+ word.slice(1)});
return results.join(' ');
}
最佳答案
What is the time-complexity of this function?
O(n).
is it right for me to say that the Time Complexity is 0(n + m), where m is the length of the words.
不,因为m 大致等于n。即使我们假设 String.slice()
的结果长度为 O(n),切片的字母总数也只是 n 的一小部分,所以它已经被考虑到复杂性中了。实际上,这可能是一个恒定时间的操作。
(分析任何 Javascript 代码的时间复杂度都有些模糊,因为该语言不保证任何操作的时间复杂度,并且运行时能够进行一些非常强大的优化。)
关于javascript - 这个函数的时间复杂度是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56316199/