88. 合并两个有序数组


双指针法(归并排序法)

import java.util.Arrays;

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {

        /**
         * 双指针遍历
         * 先将两个子数组简单合并,然后分别从子数组第一个元素开始比较,将小的放在前面
         */
        for (int i = m; i < nums1.length; i++) {
            nums1[i] = nums2[i - m];
        }

        int[] temp = Arrays.copyOf(nums1, nums1.length);
        int i = 0;
        int left = 0;
        int right = m;

        while (i < nums1.length){

            if (left == m){

                nums1[i] = temp[right];
                right++;
                i++;
            }
            else if (right == nums1.length){

                nums1[i] = temp[left];
                left++;
                i++;
            }
            else {

                if (temp[left] < temp[right]){

                    nums1[i] = temp[left];
                    left++;
                    i++;
                }
                else {

                    nums1[i] = temp[right];
                    right++;
                    i++;
                }
            }
        }
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/merge-sorted-array/