鉴于arr1& arr2,已按降序排序,输出一个数组,该数组按降序从arr1和arr2追加值

时间:2015-09-02 15:48:28

标签: java arrays

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 Actual Answer

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

Testcase2预期答案

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

当我运行我的Testcase2时,它没有给我预期的答案,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您有4种可能的结果。在最后两个结果中,当您从arr1[j]arr2[k]

获取值时,可以增加索引

你必须为所有结果做同样的事情,否则你只是重复的价值。

BTW我建议你

  • 在IDE中使用代码格式化程序,使代码更具可读性
  • 使用IDE中的调试器来逐步执行代码,以便了解它正在做什么。

答案 1 :(得分:1)

尝试这种方式:

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);

    }