gpt4 book ai didi

Java数组/逆新手

转载 作者:行者123 更新时间:2023-12-02 01:22:30 25 4
gpt4 key购买 nike

我是java语言的新手,我有一个必须解决的问题,我相当确定我已经做对了,但测试器仍然崩溃。

简单总结一下 if 要做的事情是“在数组 a 中,反转是数组中同时满足 i < j 和 a[i] > a[j] 的一对位置 i 和 j。在组合学中,数组内的反转计数是该数组“无序”程度的粗略衡量。如果数组按升序排序,则它的反转次数为零,而按逆序排序的 n 元素数组有 n( n-1)/2 个反转,可能的最大数量。此方法应该对给定数组 arr 内的反转进行计数,并返回该计数“

这是我所做的/尝试过的


import java.util.Arrays;

public class P2J1
{
public static int countInversions(int[] arr)
{
int inversions = 0;
for (int i = 0; i <= arr.length; i++){
for (int j = i+1; j < i; j++){
if (arr[i] > arr[j]){
inversions++;
}
}
}
return inversions;
}
}

/// here's the tester

@Test public void testCountInversions() {
Random rng = new Random(SEED);
CRC32 check = new CRC32();
for(int i = 0; i < 1000; i++) {
int[] a = new int[i];
for(int j = 0; j < i; j++) {
a[j] = rng.nextInt(100000);
}
check.update(P2J1.countInversions(a));
}
assertEquals(1579619806L, check.getValue());
}

最佳答案

在Java中,数组索引来自 0arr.length - 1 ,您需要更改i <= arr.length在你的代码中 i < arr.length 。否则你会得到ArrayIndexOutofBoundsException

@khelwood 的建议也是正确的。更改(int j = i+1; j < i; j++)(int j = i+1; j < arr.length; j++)

关于Java数组/逆新手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57444803/

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