简体   繁体   English

在 for 循环中 max() function 的最坏情况复杂度是多少?

[英]What is the worst case complexity of max() function inside a for loop?

I have seen the complexity of max() is O(N).我已经看到 max() 的复杂度是 O(N)。 While in program snippets(at geeksforgeeks) I had seen the complexity of such following code is O(N).在程序片段(在 geeksforgeeks)中,我看到以下代码的复杂性是 O(N)。 But how's that's possible if inside for loop these is another function of O(N).但是,如果在 for 循环中这些是 O(N) 的另一个 function,那怎么可能。 So the total complextity should be O(N^2).所以总复杂度应该是O(N^2)。 Please explain what's correct and how?请解释什么是正确的以及如何?

int x(vector<int> nums){
    int tmp;
    for(auto i=0;i<nums.size();i++){
        maximum=max(nums);
        cout<<maximum;
    }
}

Please explain what's correct请解释什么是正确的

The time complexity of the shown function is O(N*N)所示 function 的时间复杂度为 O(N*N)

and how?如何?

The function with linear complexity is called a linear number of times.具有线性复杂度的function称为线性次数。

In theory , a compiler could be smart enough to know that max returns the same value and has no side-effects, and in such case would automatically memoize the result which would result in O(N) complexity.理论上,编译器可以足够聪明地知道max返回相同的值并且没有副作用,并且在这种情况下会自动记住结果,这将导致 O(N) 复杂度。 But in practice such proof is often too hard for compilers.但在实践中,这样的证明对于编译器来说通常太难了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM