簡體   English   中英

用另一個數組中的元素替換幾乎排序的數組中的元素

[英]Replacing element in an almost sorted array with an element from another array

我的第一個數組幾乎已排序。 我需要用第二個數組中的最大可能元素替換未排序的元素。 錯誤放置的元素不會在第 0 個或 n-1 個索引上。 如果 array1[i] 小於 array1[i-1],則索引 i 是錯誤的索引。

例如:第一個輸入 5 第一個數組:2 7 8 6 13 第二個輸入 4 第二個數組 15 11 9 5 我的結果是 11

但是,如果我無法從第二個數組中獲取可能的元素,則無法打印。 例如:14 15 16 17 或者如果它有 0 個元素。

我該如何修復此代碼?

   int n1 = s.nextInt();
   int[] array1 = new int[n1];
   for (int i = 0; i < n1; i++) {
       array1[i] = s.nextInt();
   }
   
   int n2 = s.nextInt();
   int[] array2 = new int[n2];
   for (int i = 0; i < n2; i++) {
       array2[i] = s.nextInt();
   }
  
   
    int temp1=0;
    int temp2=0;
 
    
    for(int i=0; i < array1.length-1;i++) {
       if (array1[i] > array1[i+1]) {
           temp1=array1[i+1];
           temp2=array1[i+2];
           break;
       }
       
   }
   
int temp3 = 0;
   for(int j=0; j<=array2.length-1;j++) {
       if(array2[j] > temp1 && array2[j] < temp2){
           temp3 = array2[j];
           break;
       }
   }
   System.out.println(temp3);

   }

}

如下所示對代碼進行一些更改,它適用於上述問題中提到的測試用例......

1.假設索引 i+1 處的值違反了排序順序,那么你應該取 temp1 = i 和 temp2 = i+2。

2.在 array2 中找到位於 temp1 和 temp2 之間的最大值。

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
      
   Scanner s = new Scanner(System.in);      
        
   int n1 = s.nextInt();
   s.nextLine();
   int[] array1 = new int[n1];
   for (int i = 0; i < n1; i++) 
       array1[i] = s.nextInt();
   s.nextLine();
   
   int n2 = s.nextInt();
   s.nextLine();
   int[] array2 = new int[n2];
   for (int i = 0; i < n2; i++) 
       array2[i] = s.nextInt();
   s.nextLine();
  
   
    int temp1=0;
    int temp2=0;
 
    
    for(int i=0; i < array1.length-1;i++) 
       if (array1[i] > array1[i+1]){ 
           temp1=array1[i];
           temp2=array1[i+2];
       }   

   
   int temp3 = -1;
   for(int j=0; j<array2.length-1;j++) 
       if(array2[j] > temp1 && array2[j] < temp2)
           if(array2[j]>temp3)
               temp3 = array2[j];

    if(temp3 == -1)
        System.out.println("Not Possible\n");
    else
        System.out.println(temp3);

    }
}

暫無
暫無

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

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