Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
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.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
nums1和nums2都是排好序的,因此可以选取两个数组的最后一位比较最大值放在新的nums1数组的最后一位,以此类推。
但是这样会存在一个问题,即如果nums1和nums2中有两个数相等,会报错,经过反复修改,不得已把nums1已经挪到后面的数字设为-999(防止负数比较),才得以运行成功。
最方便的写法是直接吧nums2的数加在nums1后面,再整体排序,但显然,这样做浪费了时间和空间。(python3解法)
C语言
void merge(int* nums1, int m, int* nums2, int n){
int p1=m-1;
int p2=n-1;
if(p1<0){for(int i=0;i<n;i++){nums1[i]=nums2[i];}}
else if(p2>=0){
for(int i=m+n;i>0;i--){
if((p2>=0)&&(nums1[p1]<nums2[p2])){
p2=p2-1;
nums1[i-1]=nums2[p2+1];
if(i-1!=p2+1){nums2[p2+1]=-999;}
if(p2<0){p2=0;}
}
else if(p1>=0){
p1=p1-1;
nums1[i-1]=nums1[p1+1];
if(i-1!=p1+1){nums1[p1+1]=-999;}
if(p1<0){p1=0;}
}
}
}
}
Success
Details
Runtime: 4 ms, faster than 87.28% of C online submissions for Merge Sorted Array.
Memory Usage: 7 MB, less than 100.00% of C online submissions for Merge Sorted Array.
python3
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
for i in range(len(nums2)):
nums1[m+i]=nums2[i]
nums1.sort()
Success
Details
Runtime: 36 ms, faster than 99.22% of Python3 online submissions for Merge Sorted Array.
Memory Usage: 13.3 MB, less than 5.09% of Python3 online submissions for Merge Sorted Array.