LeetCode algorithm problem: merge two ordered arrays merge

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。

说明:

初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

输出: [1,2,2,3,5,6]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Ideas: the replacement string and similar spaces, https://blog.csdn.net/weixin_43777983/article/details/102297962
If the former is determined back, then, to move an array of multiple elements, time complexity is relatively high ;
if it is judged from the rear forward, a pointer pointing to define two dual element, because the two arrays are already ordered, two end of the array elements of the array is the greatest, compare the size of two elements, a large nums1 into the end of the array, then the corresponding pointer movement, and so forth, each element is moved up, the time complexity is O (n)

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int p1 = m - 1,p2 = n - 1,length = nums1.length - 1;
        while(p1 >= 0 && p2 >= 0) {
            if(nums2[p2] > nums1[p1]) {
                nums1[length--] = nums2[p2--];
            }else if(nums2[p2] < nums1[p1]) {
                nums1[length--] = nums1[p1--];
            }else{
                nums1[length--] = nums2[p2--];
                nums1[length--] = nums1[p1--];
            } 
        }
        //如果nums1元素个数为0,就把nums2的元素加入到nums1中
        while(p2 >= 0){
            nums1[length--] = nums2[p2--];
        }
    }
}
Published 219 original articles · won praise 70 · views 8638

Guess you like

Origin blog.csdn.net/weixin_43777983/article/details/103974212