【问题标题】:Replacing element in an almost sorted array with an element from another array用另一个数组中的元素替换几乎排序的数组中的元素
【发布时间】:2020-08-02 17:45:16
【问题描述】:

我的第一个数组几乎已排序。我需要用第二个数组中的最大可能元素替换未排序的元素。错误放置的元素不会在第 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);

   }

}

【问题讨论】:

    标签: java arrays algorithm sorting


    【解决方案1】:

    如下所示对代码进行一些更改,它适用于上述问题中提到的测试用例...

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-04
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 2021-12-12
      • 2019-05-01
      • 2020-03-19
      相关资源
      最近更新 更多