Java 获取数组中元素的位置 public long getMax()//获取最大值 { 如果(nelems==0){ 返回-1; } 长lngMax=arr[0]; 对于(int j=1;j

Java 获取数组中元素的位置 public long getMax()//获取最大值 { 如果(nelems==0){ 返回-1; } 长lngMax=arr[0]; 对于(int j=1;j,java,arrays,Java,Arrays,这个方法返回数组中的最大值。我应该在这里写什么逻辑,它不返回值,而是返回最大值的位置,而不使用java中的任何内置方法? 很抱歉问了个愚蠢的问题 只需稍作更改,您就可以执行以下操作: public long getMax() // get maximum value { if (nelems == 0) { return -1; } long lngMax = arr[0]; for (int j = 1; j < nelems; j++)

这个方法返回数组中的最大值。我应该在这里写什么逻辑,它不返回值,而是返回最大值的位置,而不使用java中的任何内置方法?
很抱歉问了个愚蠢的问题

只需稍作更改,您就可以执行以下操作:

public long getMax() // get maximum value
{
    if (nelems == 0) {
        return -1;
    }
    long lngMax = arr[0];
    for (int j = 1; j < nelems; j++) {
        if (lngMax < arr[j]) {
            lngMax = arr[j];
        }
    }
    return lngMax;
}
public long getIndexOfMaxValue(){
如果(nelems==0){
返回-1;
}
长结果=0;
对于(int j=1;j
像这样吗

public long getIndexOfMaxValue() {
    if (nelems == 0) {
        return -1;
    }
    long result = 0;
    for (int j = 1; j < nelems; j++) {
        if (arr[result] < arr[j]) {
            result = j;
        }
    }
    return result;
}
public int getMaxInd()//获取最大值
{
如果(nelems==0){
返回-1;
}
长lngMax=arr[0]
int lngMaxInd=0;
对于(int j=1;j
使用您自己的代码,更改为:

public int getMaxInd() // get maximum value
{
    if (nelems == 0) {
        return -1;
    }
    long lngMax = arr[0]
    int lngMaxInd = 0;
    for (int j = 1; j < nelems; j++) {
        if (lngMax < arr[j]) {
            lngMax = arr[j];
            lngMaxInd = j;
        }
    }
    return lngMaxInd;
}
public int getMaxIndex()
{
如果(nelems==0){
返回-1;
}
长lngMax=arr[0];
int指数=0;
对于(int j=1;j
public int getMax()//获取最大值
{
int指数=-1;
如果(nelems==0){
返回-1;
}
长lngMax=arr[0];
对于(int j=1;j

只要跟踪最大元素的索引,然后返回一个int而不是long,然后返回索引。

既然他想要这个位置,你不应该用
result=j
而不是
result=arr[j]
吗?是的,我的错。谢谢。:)结果类型long有什么意义?索引
j
无论如何都不会大于INT\u MAX。你真的认为你可以在循环外访问j站点吗?@ErrorAnswer确实不需要,但我认为最好使用它,而不是每次迭代都访问
arr[index]
。@eis简短回答:我认为它更好(性能方面)如果CPU缓存中没有
arr[index]
块,则访问
arr[index]
比仅访问
index
更昂贵,因此在使用大型阵列时。可能重复@Joe i已提到没有内置方法
public int getMaxIndex() 
{
    if (nelems == 0) {
        return -1;
    }
    long lngMax = arr[0];
    int index = 0;
    for (int j = 1; j < nelems; j++) {
        if (lngMax < arr[j]) {
            lngMax = arr[j];
            index = j;
        }
    }
    return index;
}
public int getMax() // get maximum value
{
    int index = -1;
    if (nelems == 0) {
    return -1;
}
   long lngMax = arr[0];
   for (int j = 1; j < nelems; j++) {
       if (lngMax < arr[j]) {
           lngMax = arr[j];
           index = j;
       }
   }
   return index;
}