gpt4 book ai didi

java - 查找最大元素的索引

转载 作者:行者123 更新时间:2023-12-01 16:52:56 26 4
gpt4 key购买 nike

我无法获取找到最大元素的索引。我知道数组中的元素可以通过 X[r] 访问,其中 r 是索引,这就是我在这里所做的,但我似乎无法仅获取索引。

代码:

public class Max {

public static void main(String[] args) {
int[] B = {-1, 2, 6, 3, 9, 2, -3, -2, 11, 5, 7};
System.out.println("max = " + maxArrayIndex(B, 0, B.length-1));
}

static int maxArrayIndex(int[] X, int p, int r) {
int q = 0;
if(p < r) {
q = (p + r)/2;
int maxLeft = maxArrayIndex(X, p, q);
int maxRight = maxArrayIndex(X, q+1, r);
int maxFinal = max(maxLeft, maxRight);
return maxFinal;
}
return X[r];
}

static int max(int p , int r) {
int maxIndex = 0;
if(p > r) {
maxIndex = p;
} else {
maxIndex = r;
}
return maxIndex;
}
}

最佳答案

public class Max {
public static void main(String[] args) {
int[] B = {-1, 2, 6, 3, 9, 2, -3, -2, 11, 5, 7};
System.out.println("max = " + maxArrayIndex(B, 0, B.length - 1));
}

static int maxArrayIndex(int[] X, int p, int r) {
int q = 0;
if (p < r) {
q = (p + r) / 2;
int maxLeft = maxArrayIndex(X, p, q);
int maxRight = maxArrayIndex(X, q + 1, r);
int maxFinal = max(X, maxLeft, maxRight);
return maxFinal;
}
// Changed from X[r] to r. This will return the index instead of the element.
return r;
}

// Added X parameter.
static int max(int[] X, int p, int r) {
int maxIndex = 0;

// Changed to compare the elements of the indexes,
// instead of comparing the indexes themselves.
if (X[p] > X[r]) {
maxIndex = p;
} else {
maxIndex = r;
}
return maxIndex;
}
}

建议的替代方案:

static int maxArrayIndex(int[] X, int p, int r) {
int currentMaxIndex = 0;
for (int i = 0; i < X.length; i++) {
if(X[i] > X[currentMaxIndex]){
currentMaxIndex = i;
}
}
return currentMaxIndex;
}

关于java - 查找最大元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com