在数组中查找最大整数?

Rac*_*hel 4 arrays algorithm

我有两个数组,一个非常大(超过百万个条目),而另一个数组很小(少于1000个条目),在数组中查找所有条目的最大数量的最佳方法是什么?

谢谢.

And*_*are 15

如果数组未排序,则必须执行线性搜索以查找每个数组中的最大值.如果数组排序,则只需从每个数组中取出第一个或最后一个元素(取决于排序顺序).


Isa*_*ler 5

如果您考虑一下,如果要查找最高值,则必须检查所有值.没有办法解决这个问题(除非对数组进行排序,这很简单 - 只需要取每个数组的最后一个(或者先排序),然后选择最大的数组.例:

int highest = array1[i]; // note: don't do this if the array could be empty
for(int i = 0; i < array1.length; i++) {
    if(highest<array1[i]) highest = array1[i];
}
for(int i = 0; i < array2.length; i++) {
    if(highest<array2[i]) highest = array2[i];
}  
// highest is now the highest
Run Code Online (Sandbox Code Playgroud)