簡體   English   中英

Java實驗室-計數運行

[英]Java Lab - Counting Runs

語言:Java

沒有語法錯誤,並且通過了編譯器,但我的測試器失敗。 有人可以告訴我我在這里做錯了什么嗎?

這是實驗文本說明該方法的用途:“計算從索引開始到索引結束(包括兩端)的arr子數組中有多少次運行(連續的相等元素塊)”

另外:本實驗不允許使用任何循環,但是if-else語句是可以的。

參數:arr =數組,開始/結束=開始/結束的索引

public class Recursion {
    int countRuns(int[] arr, int start, int end) {
        if (start >= end) 
            return 0; //checks for null arrays 

        int counter = 0; 
        if (start == 0)
            counter = 1; 

        //check the next element for similarity/difference 
        if (arr[start] != arr[start+1])
            counter = 1; 

        return counter + countRuns(arr, start + 1, end);  
    }
}

我認為您只是稍微錯過了開始和結束時的條件。

public class Recursion {
    int countRuns(int[] arr, int start, int end) {
        if (start > end) 
            return 0; //checks for null arrays 

        if (start == end) // the indices are inclusive
            return 1;

        int counter; 
        if (arr[start] == arr[start + 1]) {
            counter = 0; // we'll still be in the same run, if they're equal
        } else {
            counter = 1; // otherwise it's a new run
        }

        return counter + countRuns(arr, start + 1, end);
    }
}

暫無
暫無

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

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