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 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]
Constraints:
-10^9 <= nums1[i], nums2[i] <= 10^9 nums1.length == m + n nums2.length == n
解题思路: 因为nums1长度为nums1和nums2 >0的值的总和,所以双指针,倒叙比较插入
代码: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.
"""
p=m-1
q=n-1
r=m+n-1
while p>=0 and q>=0:
if nums1[p]>nums2[q]:
nums1[r]=nums1[p]
p=p-1
r=r-1
else:
nums1[r]=nums2[q]
q=q-1
r=r-1
nums1[:q+1]=nums2[:q+1]
if __name__ == '__main__':
print(Solution().merge([1,2,3,0,0,0],3,[2,5,6],3))
空间复杂度:O(1),时间复杂度O(m+n)
java 题解 因为nums1,nums2都是排好序的 nums1的最后一位开始逆序添加
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i1=m-1;
int i2=n-1;
int cur = m+n-1;
//i2<0时,说明整个nums1数组排好序了
while(i2>=0){
//i1<0,可能还需要把nums2剩余元素添加进来
while(i1>=0 && nums1[i1]>nums2[i2]){
nums1[cur--]=nums1[i1--];
}else{
nums1[cur--]=nums2[i2--];
}
}
}
}
空间复杂度:O(1),时间复杂度O(m+n)