zoukankan      html  css  js  c++  java
  • 剑指offer编程题Java实现——面试题4后的相关题目

    题目描述:

    有两个排序的数字A1和A2,内存在A1的末尾有足够多的空余空间容纳A2.请实现一个函数,把A2中的所有数字插入到A1中并且所有的数字是排序的。

    还是利用从后向前比较两个数组中的数字的方式来实现。

     1 package Solution;
     2 
     3 
     4 /**
     5  * 有两个排序的数字A1和A2,内存在A1的末尾有足够多的空余空间容纳A2.
     6  * 请实现一个函数,把A2中的所有数字插入到A1中并且所有的数字是排序的。
     7  * @author GL
     8  * 本题应该注意Java中不可变数组的性质,所以用创建新数组接受插入排序后的元素
     9  */
    10 public class No4InsertSortedArrays {
    11 
    12     public static void main(String[] args) {
    13         int[] array1={4,5,6,7,8,10};
    14         int[] array2={1,2,3,4,5};
    15         int[] temp=insertSortedArrays(array1,array2);
    16         for(int k=0;k<temp.length;k++){
    17             System.out.print(temp[k]);
    18         }
    19     }
    20 
    21     /*
    22      * 从头到尾比较两个数组中的数字,把较大的数字复制到新数组的合适位置。
    23      */
    24     public static int[] insertSortedArrays(int[] array2,int[] array1){
    25         if(array1==null||array2==null)
    26             return null;
    27         int i=array1.length-1;
    28         int j=array2.length-1;
    29         int n=array1.length+array2.length-1;
    30         int[] temp=new int[array1.length+array2.length];
    31         while(n>=0){
    32             if(i>=0&&j>=0){
    33                 if(array1[i]>array2[j]){
    34                     temp[n]=array1[i];
    35                     n--;
    36                     i--;
    37                 }else if(array1[i]<array2[j]){
    38                     temp[n]=array2[j];
    39                     n--;
    40                     j--;
    41                 }else if(array1[i]==array2[j]){
    42                     temp[n]=array2[j];
    43                     temp[n-1]=array1[i];
    44                     n=n-2;
    45                     i--;
    46                     j--;
    47                 }
    48             }else if(i>=0&&j<0){
    49                 temp[n--]=array1[i--];
    50             }else if(i<0&&j>=0){
    51                 temp[n--]=array2[j--];
    52             }
    53             
    54         }
    55         return temp;
    56     }
    57 }
  • 相关阅读:
    8.13实习报告
    8.10实习报告
    8.9实习报告
    8.8实习报告
    8.7实习报告
    关于线索二叉树建立和遍历
    main函数的位置可以任意
    返回指针值的函数和函数指针的区别
    runtime error: store to address 0x625000002048 with insufficient space for an object of type 'double' (solution.c) 0x625000002048: note: pointer points here
    m=-n++
  • 原文地址:https://www.cnblogs.com/gl-developer/p/6435466.html
Copyright © 2011-2022 走看看