簡體   English   中英

給定已經按降序排列的arr1和arr2,輸出一個數組,該數組以降序附加來自arr1和arr2的值

[英]Given arr1 & arr2, that have been sorted in descending order, output an array which appends values from both arr1 and arr2 in descending order

public int[] join(int[] arr1,int[] arr2){

    int[] joinArr=new int[arr1.length + arr2.length];
    int j=0,k=0;
    for(int i=0;i<joinArr.length;i++){
        if(j==arr1.length){
            joinArr[i]=arr2[k];
        }
        else if(k==arr2.length){
            joinArr[i]=arr1[j];
        }
        else if(arr1[j]>arr2[k]){
            joinArr[i]=arr1[j];
            j++;
        }
        else{
            joinArr[i]=arr2[k];
        k++;
        }

    }    

    return joinArr;

}

Testcase1參數

{100,90,80,70,60} {105,95,85,75,65}

Testcase1實際答案

{105,100,95,90,85,80,75,70,65,60}

Testcase1預期答案

{105,100,95,90,85,80,75,70,65,60}

Testcase2參數

{100,90,80,70,60} {105}

Testcase2實際答案

{105,100,100,100,100,100}

Testcase2預期答案

{105,100,90,80,70,60}

當我運行Testcase2時,它沒有給我預期的答案,如何解決此問題?

您有4個可能的結果。 在最后兩個結果中,當您從arr1[j]arr2[k]取值時,您將增加索引

您必須對所有結果都執行相同的操作,否則,您只是重復獲得的價值。

順便說一句我建議你

  • 在IDE中使用代碼格式化程序使代碼更具可讀性
  • 在您的IDE中使用調試器來逐步檢查代碼,以便您了解它在做什么。

嘗試這種方式:

public static int[] join(int[] arr1,int[] arr2){
        int[] joinArr=new int[arr1.length + arr2.length];
        int i=0,j=0,k=0;
        while(i<arr1.length && j<arr2.length){  // coping from both the array while one of them is exhausted
            if( arr1[i]>arr2[j]){
                joinArr[k++]=arr1[i++]; // coping from arr1 and update the index i and k.
            }else if(arr1[i]<arr2[j]){
                joinArr[k++]=arr2[j++]; // coping from arr2 and update the index j and k.
            }else{
                joinArr[k++]=arr2[j++]; // coping from any of arr1  or arr2 and update the index i,j and k. 
                i++;
            }


        }  
        if(i<arr1.length){  // coping from  the array arr1 since arr2 is exhausted

             while(i<arr1.length ){
                 joinArr[k++]=arr1[i++];
             }
        }

        if(j<arr2.length){  // coping from  the array arr2 since arr1 is exhausted

             while(j<arr2.length ){
                 joinArr[k++]=arr2[j++];
             }
        }

        return Arrays.copyOf(joinArr, k);

    }

暫無
暫無

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

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