[英]Worst-case time complexity of an algorithm with 2+ steps
My goal is to write an algorithm that checks if an unsorted array of positive integers contains a value x and x^2 and return their indices if so.我的目标是编写一个算法来检查未排序的正整数数组是否包含值 x 和 x^2,如果包含,则返回它们的索引。 I've solved this by proposing that first you sort the array using merge sort, then perform binary search for x, then perform binary search for x^2.
我已经解决了这个问题,建议首先使用归并排序对数组进行排序,然后对 x 执行二进制搜索,然后对 x^2 执行二进制搜索。 I then wrote that "since binary search has worst-case runtime of O(log n) and merge sort has worst-case runtime of O(n log n), we conclude that the worst-case runtime of this algorithm is O(n log n)."
然后我写道:“由于二分搜索的最坏情况运行时间为 O(log n),归并排序的最坏情况运行时间为 O(n log n),我们得出结论,该算法的最坏情况运行时间为 O(n记录 n)。” Am I correct in my understanding that when analyzing the overall efficiency of an algorithm that involves steps with different runtimes, we just take the one with the longest runtime?
我的理解是否正确,在分析涉及具有不同运行时间的步骤的算法的整体效率时,我们只采用运行时间最长的那个? Or is it more involved than this?
或者它比这更复杂? Thanks in advance!
提前致谢!
Since O(log n) < O(n log n)
:由于
O(log n) < O(n log n)
:
O(n log n) + O(log n) + O(log n) = O(n log n)
So the time complexity of the hole algorithm is O(n log n)
.所以打洞算法的时间复杂度是
O(n log n)
。
Your question is a bit ambigous.你的问题有点模棱两可。 Do you get
你明白了吗
[a,b,c...]
and a specific x
to search for as parameter?[a,b,c...]
和一个特定的x
作为参数搜索? or要么
(x,y)
with x^2 = y
contained in the list?(x,y)
且x^2 = y
? Now as you have cleared it's the first, the answer is O(n) , because you just have to iterate over the list (no need to sort or binary search) and check for each element if it's equal to x
or x^2
.现在你已经清除了它是第一个,答案是O(n) ,因为你只需要遍历列表(不需要排序或二进制搜索)并检查每个元素是否等于
x
或x^2
。 If you find both, the list fulfills the condition.如果两者都找到,则该列表满足条件。
function match(list, x) {
let ix = -1, ixx = -1;
for (let i = 0; i< list.length && (ix == -1 || ixx == -1); i++) {
if (i == x) ix = i;
if (i == x*x) ixx = i;
}
return [ix, ixx];
}
This returns the indexes of x
and x^2
or, if not found -1
for the respective index.这将返回
x
和x^2
的索引,或者如果没有找到相应索引的-1
。 It returns, once both values are found in the list一旦在列表中找到两个值,它就会返回
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.