leetcode-88- merge two ordered arrays

description:

Given two ordered arrays of integers and nums2 nums1, incorporated into the nums2 nums1 in an ordered array such as a num1. 

Description: 
Initialization nums1 nums2 and the number of elements of m and n. 
You can assume nums1 sufficient space (space equal to or greater than m + n) to save the elements of nums2. 
Example: 

Input: 
nums1 = [1,2,3,0,0,0], m =. 3 
nums2 = [2,5,6], n-=. 3 

Output: [1,2,2,3,5,6 ]

  

answer:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int tail = m + n - 1;
        int i = m - 1;
        int j = n - 1;
        while (j != -1) {
            if (i == -1) {
                nums1[tail--] = nums2[j--];
            } else if (nums1[i] >= nums2[j]) {
                nums1[tail--] = nums1[i--];
            } else if (nums1[i] < nums2[j]) {
                nums1[tail--] = nums2[j--];
            }
        }
    }
}

  

Comments: to minimize the movement of the array elements

 

java data copy 

System.arraycopy (nums2, 0, nums1, m, n-); 
Arrays.sort (nums1);

  

leetcode solution - read it more elegant

class Solution {
  public void merge(int[] nums1, int m, int[] nums2, int n) {
    // two get pointers for nums1 and nums2
    int p1 = m - 1;
    int p2 = n - 1;
    // set pointer for nums1
    int p = m + n - 1;

    // while there are still elements to compare
    while ((p1 >= 0) && (p2 >= 0))
      // compare two elements from nums1 and nums2 
      // and add the largest one in nums1 
      nums1[p--] = (nums1[p1] < nums2[p2]) ? nums2[p2--] : nums1[p1--];

    // add missing elements from nums2
    System.arraycopy(nums2, 0, nums1, 0, p2 + 1);
  }
}

  

Reference: https://leetcode-cn.com/problems/merge-sorted-array/solution/he-bing-liang-ge-you-xu-shu-zu-by-leetcode/

Guess you like

Origin www.cnblogs.com/wangsong412/p/11801207.html
Recommended