Merge two ordered arrays [leetcode]

1. Question:

You are given two integer arrays nums1 and nums2 arranged 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 array is 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 elements that should be merged and the last n elements are 0 and should be ignored. The length of nums2 is n.

2. Ideas:

Just compare the largest elements in the two arrays each time.

① First, take the largest elements in the two arrays for comparison. The larger element is placed at the m+n-1 position of the num1 array. Then the original position index (m or n) of the current element is subtracted, and the purpose is downward. An element to be compared, and our num1 empty position index also needs to be subtracted, with the purpose of pointing to the next empty position. We use m+n-1 to represent the empty position index here. When m or n is subtracted, The empty position index will also be reduced accordingly;

② This comparison process needs to be repeated. When will it stop? When the comparison position has reached the far left, that is, when the index is 0, we can no longer compare, because m-1 and n-1 here are the respective indices of the two arrays, and the loop condition is m > 0 && n > 0, as long as an array is traversed to the end, exit the loop;

③ After the loop exits if the conditions are not met, if n<0, but m>0 or both n and m are less than 0, it means that all the elements in num2 have been inserted into num1, and the merger is completed at this time;

④ If m<0, but n>0, this situation means that all the elements in num1 have been compared, and only the elements in num2 are left waiting to be inserted, so at this time we also need a while loop to compare the elements in num2 Insert into num1 in turn. The empty position index is still m+n-1. Each time n is subtracted until n equals 0.

3. Code implementation:

class Solution {
    
    
    public void merge(int[] nums1, int m, int[] nums2, int n) {
    
    
        while (m > 0 && n > 0) {
    
    
            if(nums1[m - 1] > nums2[n - 1]) {
    
    
                nums1[m + n - 1] = nums1[m - 1];
                m--;
            } else {
    
    
                nums1[m + n - 1] = nums2[n - 1];
                n--;
            }
        }

        while (n > 0) {
    
    
            nums1[m + n - 1] = nums2[n - 1];
            n--;
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_52861684/article/details/132384708