您的位置:首页 > 职场人生

剑指offer编程题Java实现——面试题4后的相关题目

2017-02-23 21:10 363 查看
题目描述:

有两个排序的数字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
=array1[i];
35                     n--;
36                     i--;
37                 }else if(array1[i]<array2[j]){
38                     temp
=array2[j];
39                     n--;
40                     j--;
41                 }else if(array1[i]==array2[j]){
42                     temp
=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 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐