簡體   English   中英

Java數組/逆向新手

[英]Java array/inverse novice

我是Java語言的新手,我有一個必須解決的問題,我很確定自己做對了,但測試儀仍然崩潰。

如果必須做的簡短摘要是“在數組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++)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM