[英]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]
取值時,您將增加索引
您必須對所有結果都執行相同的操作,否則,您只是重復獲得的價值。
順便說一句我建議你
嘗試這種方式:
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.