【问题标题】:Array swapLargest not passing all tests, BASIC JAVA数组 swapLargest 未通过所有测试,BASIC JAVA
【发布时间】:2016-11-07 09:38:43
【问题描述】:

由于是周末,我已经尝试完成这个问题大约 2 天了,我无法联系学校的任何导师。我创建了一个循环,在非空数组中找到最大值,然后将该数组中最大数字的最低索引与数组中的最后一个值交换。

例如

swapLargest([1, 7, 5, 7, 4, 2]) → [1, 2, 5, 7, 4, 7]

但运行它会出现

[1, 7, 5, 7, 2, 4]

这是我的代码

int[] swapLargest(int[] a) {

 int max = Integer.MIN_VALUE;

for(int i = 1; i <a.length; i++){ // starting from 0
  if(a[i]  > max){
    max = a[i];
    max = i;

  }

}
 int temp = a[max];
 a[max]=a[a.length-1];
 a[a.length-1] = temp;
 return a;



}

最后是问题的链接:http://codingbat.com/prob/p227094 如果你想用我的测试你的结果。到目前为止,这将通过 4/11 测试。

我真的是编程新手,如有任何提示,将不胜感激。

谢谢!

【问题讨论】:

  • max = a[i]; max = i 您将两次分配给同一个变量-第一次分配的结果被第二次覆盖。也许您需要分配给两个不同的变量。

标签: java arrays indexing


【解决方案1】:

您可以将最大值的索引存储在单独的变量中:

int[] swapLargest(int[] a) {

 int max = Integer.MIN_VALUE;
 int maxI = 0 ;

for(int i = 0; i < a.length; i++){
  if(a[i]  > max){
    max = a[i];
    maxI = i;

  }

}
 int temp = a[maxI];
 a[maxI]=a[a.length-1];
 a[a.length-1] = temp;
 return a;
}

【讨论】:

  • 它会在检查 for 循环的条件时给出语法错误,还有一个逻辑错误是您开始遍历数组以从索引 1 中找到最大元素所以如果最大元素在第一个位置,此代码将在那里失败。
猜你喜欢
  • 2016-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 2014-06-14
  • 2019-12-10
  • 2018-10-12
  • 1970-01-01
  • 2020-08-08
相关资源
最近更新 更多