LeetCode 88 Merge Two Sorted Arrays

1. Description of the topic

  You are given two integer arrays nums1 and nums2 in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2, respectively.
Please merge nums2 into nums1 so that the merged arrays are also arranged in non-decreasing order.
Note: Ultimately, the merged array should not be returned by the function, but stored in the array nums1. To cope with this situation, the initial length of nums1 is m + n, where the first m elements represent the elements that should be merged, and the last n elements are 0 and should be ignored. The length of nums2 is 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: Need to combine [1,2,3] and [2,5,6].
The combined result is [1,2,2,3,5,6], where the elements in nums1 are marked in bold italics.
Example 2:
  Input: nums1 = [1], m = 1, nums2 = [], n = 0
  Output: [1]
Explanation: Need to combine [1] and [].
The combined result is [1].
Example 3:
  Input: nums1 = [0], m = 0, nums2 = [1], n = 1
  Output: [1]
Explanation: The arrays to be merged are [] and [1].
The combined result is [1].
Note that since m = 0, there are no elements in nums1. The only 0 in nums1 is to ensure that the merged result can be stored in nums1 smoothly.

2. Ideas

  The double pointer method
  uses the pointers n and m to represent the subscripts of nums2 of nums1, respectively. The sizes of the two array elements are compared from the end of the array, and the corresponding values ​​are assigned from the end of nums1 after the comparison.

class Solution {
    
    
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    
    
        //双指针法
        int index = m+n-1;
        while(n >= 1 && m >= 1){
    
    
            //当前比较 nums2 > nums1
            if(nums2[n - 1] >= nums1[ m -1 ]){
    
    
                nums1[index] = nums2[n - 1];
                n--;
            }
            //当前比较 nums1 > nums2
            else{
    
    
                nums1[index] = nums1[m - 1];
                m--;
            }
            index--;
        }
        //当 nums2 中还有元素时
        if(m == 0){
    
    
            while(n >= 1){
    
    
                nums1[index--] = nums2[n - 1];
                n--;
            }
        }
    }
};

It's not easy to organize your likes and attention, which is a great encouragement to me

insert image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324379434&siteId=291194637