簡體   English   中英

通過使用遞歸查找數組是否對稱

[英]Find if array is Symmetric by using recursion

基本上,我有關於遞歸的大學工作,但是在解決此問題時遇到了問題。 我必須創建兩種方法,一種稱為getLastElement和isSymmetric。 getLastElement只能從數組訪問索引0。 如果數組是對稱的或為0,則isSymmetric必須顯示true。它必須使用array [0]和array.length。 它也可以使用Arrays.copyOfRange()

我已經做過isSymmetric,但是沒有getLastElement,我想我缺少了一些東西,因為我不知道如何將getLastElement合並到其中。 我知道我沒有使用array [0],但是我無法使用它。

這是我的代碼:

public static int isSymmetric(int array[], int begin, int end) 
    { 

        if (begin >= end) { 
            return 1; 
        } 
        if (array[begin] == array[end]) { 
            return isSymmetric(array, begin + 1, end - 1); 
        } 
        else { 
            return 0; 
        } 
    } 


        public static void main (String[] args) { 
        int array[] = { 1, 2, 3, 2, 1 }; 

        if (isSymmetric(array, 0, array.length - 1) == 1) 
            System.out.print( "true"); 
        else
            System.out.println( "false"); 
        } 

我只想像現在一樣打印,但是將getLastElement合並到isSymmetric中。

無需發送整個數組以及索引的beginend ,您只需在這兩個索引之間使用數組的副本即可。 這樣做將允許您使用getLastElement函數(請參見代碼)。

// I am assuming this function returns the 
// 0th-indexed element of the array.
public static int getLastElement(int[] array) {
    return array[0];    
}

public static int isSymmetric(int[] array) {
    if(array.length <= 1) return 1;

    // check if the first and the last element are equal
    if(getLastElement(array) == array[array.length -1])

        // copy the remaining array (leaving first and last element)
        return isSymmetric(Arrays.copyOfRange(array, 1, array.length-1));

    return 0;
}


public static void main (String[] args) { 
    int array[] = { 1, 2, 3, 2, 1 }; 

    if (isSymmetric(array) == 1) 
        System.out.println( "true"); 
    else
        System.out.println( "false"); 
} 

getLastElement實際上是返回數組的第一個元素,因此,如果您看到它實際上是一種getFristElement函數。 這樣做是因為問題指出該函數僅允許訪問數組的第0個索引。

暫無
暫無

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

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