合并两个有序数组(c#)
问题描述
给定两个非递减的整型数组,数组中数据的个数别为m,n。
数组1的大小为m+n,前面存放m个数据,后面存放n个0。数组2存放n个数据。
将数组2合并到数组1,并其数组1仍然保持非递增的顺序。
示例
- 示例1
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
解决方案描述
- 首先判断数组1的大小,如果不等于m+n,1. 则返回空。
- 设定数组1中与数组2进行比较的开始下标变量,并初始化为0。
数组1中当前数据个数变量,并初始化为m,数组2的值小于数组1的值的存在变量,并初始化为false。 - 循环遍历数组2,并执行以下操作:
- 循环遍历数组1,并执行以下操作:
如果数组2的当前值小于数组1的当前值,
则将数组1中的当前值与当前值以后的值往后移动一位。
将数组2的当前值赋值给数组1的当前值。
数组1中当前数据个数变量加1,
与数组2进行比较的开始下标变量设为数组1的当前值下标加1,
数组2的值小于数组1的值的存在变量为true,并且退出数组1的循环。
- 如果数组2的值小于数组1的值的存在变量为false,则执行以下操作:
将数组2的当前值赋值给数值1的下标为[数组1中当前数据个数变量]所对应的数值。
与数组2进行比较的开始下标变量设为数组1中当前数据个数,
数组1中当前数据个数变量加1。
具体代码见下面的链接
更多推荐


所有评论(0)