Given two sorted integer arrays num1 and num2, merge nums2 into nums1 as one sorted array.
给定两个有序数组,将数组num2 添加到num1 中,使得成为一个新的有序数组
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space(size that is greater or equal to m +n to hold additional elements from nums2.
思路:
- 初始化两个数组nums1 和nums2的元素数量分别为m和n
- 在第二个数组中取一个数num,遍历第一个数组,找到一个位置 j,使得在位置 j -1 处元素小于 num ,而 位置 j+1 处大于 num
- 插入到该位置:将后面的元素全部后移(我觉得可以用链表实现,因为链表添加元素好像比较简单,不够现在还不是很懂链表)
代码:
public class Merge { /* *将两个有序数组组成一个有序数组 */ public void merge (int[] nums1, int m,int[] nums2,int n ) { int j=0; for (int i = 0; i < n; i++) { int num=nums2[i]; while(num>nums1[j]&&j<m){ /*遍历第一数组,找到应有的位置*/ j++; } int k=m; while(k>j) { /*从这个位置开始所有后移*/ nums1[k]=nums1[k-1]; k--; } m++; nums1[j]=num; } } }
调用:
public class Main { public static void main(String[] args) { Merge merge=new Merge(); /*确保有足够的长度>=m+n*/ int[] a= {23, 43,56,0,0,0}; int[] b= {2,3,5}; int m=3,n=3; merge.merge(a,m,b,n); for (int i = 0; i < a.length; i++) { System.out.print(a[i]+" "); } } }