[LeetCode-Java Exercise] 88. Combine two ordered arrays (simple)

1. Title description

Insert picture description here

2. Problem solving ideas

Generally speaking, for an ordered array, the time complexity of O(n + m) can be achieved through the double pointer method.
The most straightforward algorithm implementation is to set the pointer p1 to the beginning of nums1 and p2 to the beginning of nums2, and put the minimum value in the output array at each step.
Since nums1 is an array for output, the first m elements in nums1 need to be placed elsewhere, which requires O(m) space complexity.

3. Code implementation

class Solution {
    
    
  public void merge(int[] nums1, int m, int[] nums2, int n) {
    
    
    // Make a copy of nums1.
    int [] nums1_copy = new int[m];
    System.arraycopy(nums1, 0, nums1_copy, 0, m);

    // Two get pointers for nums1_copy and nums2.
    int p1 = 0;
    int p2 = 0;

    // Set pointer for nums1
    int p = 0;

    // Compare elements from nums1_copy and nums2
    // and add the smallest one into nums1.
    while ((p1 < m) && (p2 < n))
      nums1[p++] = (nums1_copy[p1] < nums2[p2]) ? nums1_copy[p1++] : nums2[p2++];

    // if there are still elements to add
    if (p1 < m)
      System.arraycopy(nums1_copy, p1, nums1, p1 + p2, m + n - p1 - p2);
    if (p2 < n)
      System.arraycopy(nums2, p2, nums1, p1 + p2, m + n - p1 - p2);
  }
}

Guess you like

Origin blog.csdn.net/weixin_48683410/article/details/114198764