今天要挑战的合并两个已排序的阵列,这题的题目要求也很有趣,与以往有些不同,让我们一起来挑战看看!
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Example 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.
Example 2:
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].
Example 3:
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.
这个题目叙述真的是有点长,我长话短说简单说明,这题的要求是,题目会给我们两个已经排序好的一维阵列nums1与nums2,并希望我们能够将两个合并过後,仍然保持排序。
特别的是,这题并不是要求我们回传一个阵列,而是希望我们能不用额外的空间,直接利用nums1把排序好的阵列存进去!那当然,题目有特别设计过nums1的空间刚好可以放得下合并後的两个阵列(留空的空间以0表示),而且题目也会给我们两个参数m与n分别代表nums1与nums2的阵列中数字的个数。
这题其实可以用一个小巧思,不需要用任何内建的函式只需要依靠一个回圈,就能达到将两个排序好的阵列合并的效果。由於我们知道两个阵列内分别都是排序好的数字,因此可以分别利用参数m与n,从阵列的最後一个数字开始进行两两比对,如果比较大的就将其直接放进nums1的尾巴,如果比较小的数就继续留着等待比对,最多经过m+n次的回圈後,就一定能将两个阵列合并,如果nums2优先排序完,甚至可以直接中断回圈,就能达到题目要求。
我们这边用题目叙述中的example1当例子。首先
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
我们比对nums1真正的最後一个数字3与nums2最後一个6,这边6比较大,所以把6放进nums1的尾巴,会变这样
nums1 = [1,2,3,0,0,6]
而後下一次轮到nums2中的5和nums1中一样是3,依序用同样的逻辑比对,会变这样
nums1 = [1,2,3,0,5,6]
按照这样的方法,会依序有下列变化
nums1 = [1,2,3,3,5,6]
nums1 = [1,2,2,3,5,6]
到这边nums2的东西全部比完,可以中断回圈,就是题目要求了。
以下为python3的程序码
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
for i in range(1, m + n + 1):
if n == 0:
break
elif m == 0:
nums1[-i] = nums2[n - 1]
n -= 1
continue
if nums1[m - 1] < nums2[n - 1]:
nums1[-i] = nums2[n - 1]
n -= 1
else:
nums1[-i] = nums1[m - 1]
m -= 1
以下是C++的程序码
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
for(int i=m+n-1;i>-1;i--){
if(m==0){
nums1[i] = nums2[n-1];
n -= 1;
continue;
}
else if(n==0){
break;
}
if(nums2[n-1] >= nums1[m-1]){
nums1[i] = nums2[n-1];
n -= 1;
}
else{
nums1[i] = nums1[m-1];
m -= 1;
}
}
}
};
<<: Material UI in React [Day 6] Theme (Globals) & Inputs (Buttons)
今天不想提软件相关的心得,想来聊一点工作沟通相关的事情。在开始分享之前,必须要先提到,我知道自己不是...
开始之前先送上菜鸡的code 这是我第一次实作RWD的网页,又因为最近同步在看Bootstrap。 ...
POSIX Threads 是一套符合 POSIX 标准的 API,方便开发者设计出 User-le...
第三天 各位点进来的朋友,你们好阿 小的不才只能做这个系列的文章,但还是希望分享给点进来的朋友,知道...