鉴于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

查看:178
本文介绍了鉴于ARR1&安培; ARR2,已在递减顺序被排序,输出,附加按降序来自ARR1价值观和ARR2数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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参数

Testcase1 Parameters

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

Testcase1实际答案

Testcase1 Actual Answer

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

Testcase1预期的答案

Testcase1 Expected Answer

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

Testcase2参数

Testcase2 Parameters

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

Testcase2实际答案

Testcase2 Actual Answer

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

Testcase2预期的答案

Testcase2 Expected Answer

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

当我跑我的Testcase2,它并没有给我预期的答案,我怎么能解决这个问题?

When I run my Testcase2, it doesn't give me the expected answer , how could I fix this problem?

推荐答案

试试这个方法:

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

    }

这篇关于鉴于ARR1&安培; ARR2,已在递减顺序被排序,输出,附加按降序来自ARR1价值观和ARR2数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆