空间复杂度O(n)方式
数组1:{1, 3, 5, 7, 9}
数组2:{2, 5, 7, 9, 13}
合并后:[1,2,3,5,5,7,7,9,9,13]
/**
* 两个数组合并
*/
public class ArrayMerge {
public static void main(String[] args) {
int[] sum1 = {1, 3, 5, 7, 9};
int[] sum2 = {2, 5, 7, 9, 13};
merge(sum1, sum1.length, sum2, sum2.length);
System.out.println(JSONObject.toJSONString(newNums));
}
private static List<Integer> newNums;
public static void merge(int[] nums1, int m, int[] nums2, int n) {
newNums = new ArrayList<Integer>(m + n);
int index1 = 0;
int index2 = 0;
while (index1 < m || index2 < n) {
if (index1 < m && index2 < n) {
int mEl = nums1[index1];
int nEl = nums2[index2];
if (mEl > nEl) {
newNums.add(nEl);
index2++;
} else {
newNums.add(mEl);
index1++;
}
continue;
}
if (index1 < m) {
newNums.add(nums1[index1]);
index1++;
continue;
} else {
newNums.add(nums2[index2]);
index2++;
}
}
}
}
利用成型工具:
public void merge(int[] nums1, int m, int[] nums2, int n) {
/**
* 1:将nums2拷贝到nums1中
* 2:从nums2下标0开始拷贝
* 3:nums1
* 4:nums1的第几个元素开始依次存放nums2
* 5:nums2的长度
*/
System.arraycopy(nums2,0,nums1,m,n);
Arrays.sort(nums1);
}