【问题标题】:get the position of an element in an array获取数组中元素的位置
【发布时间】:2014-10-09 14:42:50
【问题描述】:
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;
}

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

【问题讨论】:

标签: java arrays


【解决方案1】:

您可以做的改动很少:

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;
}

【讨论】:

  • 你不应该把result = j而不是result = arr[j],因为他想要这个职位吗?
  • 是的,我的错。谢谢。 :)
  • 结果类型 long 有什么意义? index j 无论如何都不会大于 INT_MAX。
【解决方案2】:

像这样?

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;
}

【讨论】:

  • 你真的认为你可以访问 j out site the loop 吗?
【解决方案3】:

使用你自己的代码,改成这样:

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;
}

【讨论】:

  • @wrongAnswer 并不需要,但我认为最好使用它而不是在每次迭代时访问arr[index]
  • @eis 简短回答:我认为在大型阵列的情况下(性能)更好,因为如果arr[index] 块不在您的范围内,则访问arr[index] 比仅访问index 更昂贵CPU 缓存。
【解决方案4】:
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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多