How to find maximum value in any range of an array in log(n) time? [closed]

半城伤御伤魂 提交于 2019-12-13 21:34:37

问题


E.g. Array: {1, 5, 2, 3, 2, 10}

Range: 0-1 Answer: 5 Range: 2-4 Answer: 3 Range: 0-5 Answer: 10 etc.


回答1:


If the array is not sorted, then there is no way to do what you're asking for.

To find the maximum you at least need to inspect all elements in the range, which takes O(n).

If you allow some form of preprocessing of the data, it's easy. You could just build an n2 lookup table with the answers. Then you could find the maximum for any range in constant time.




回答2:


This is impossible. You'd have to visit every element.

If your array is sorted a-priori, then it's O(1) operation.




回答3:


See also here: What is the best way to get the minimum or maximum value from an Array of numbers?

As the others pointed out it's impossible




回答4:


@Daniel Talamas if i understood you correctly, you wanted this :

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int maxlement(int range1,int range2) {
std::vector<int> v{ 1, 5, 2, 3, 2, 10 };
std::vector<int>::iterator result;

result = std::max_element(v.begin()+range1, v.begin()+range2+1);
int dist = std::distance(v.begin(), result);
return v[dist];

}
int main() {
int range1,range2;
cout<<"From ";
cin>>range1;
cout<<"To ";
cin>>range2;
cout<<"Max Element Is "<<maxlement(range1,range2);
return 0;
}


来源:https://stackoverflow.com/questions/9467247/how-to-find-maximum-value-in-any-range-of-an-array-in-logn-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!