LeetCode brush question: Double pointer [88. Merge two ordered arrays] - Java version

Double pointer: merge two sorted arrays

I just record my own process of brushing the questions, and I have referred to various solutions for the answers.

Thank you for correcting me if I make any mistakes!

Reference: LeetCode 101: A LeetCode Grinding Guide (C++ Version) Author: Gao Chang Chang Gao

Source of questions: Question Bank - LeetCode, the global geek's favorite technology growth platform (leetcode-cn.com)

A. Double pointer thinking

  • Since the two arrays are already sorted, we can place two pointers at the end of the two arrays, m − 1 bits of nums1 and n − 1 bits of nums2.

  • Compare the values ​​corresponding to the two pointers, copy the larger number to the back of nums1 each time, and then move forward one bit. Since we're also targeting the end of nums1, we also need a third pointer for copying.

  • Note that nums1 的 m − 1 位and nums1 的末尾are not in the same position.

B. Concrete implementation

  • Directly use m and n as the pointers of the two arrays, and create an additional pos pointer with the starting position of m+n−1. Every time you move forward m or n, you also move pos forward.

  • It should be noted here that if the numbers of nums1 have been copied, don't forget to continue copying the numbers of nums2; if the numbers of nums2 have been copied, the remaining numbers of nums1 do not need to be changed, because they have been sorted.

  • Tips for ++ and --: both a++ and ++a add 1 to a, but the return value of a++ is a, and the return value of ++a is a+1. If you just want to increase the value of a without returning a value, it is recommended to use ++a, which will run slightly faster.

c. to think

  • The two pointers point to the subscript of the last numerical value, and they are compared in pairs , and the one with the larger numerical value is covered at the end.

  • The judgment of greater than rather than greater than or equal to (nums1[m] > nums2[n]) is to end the nums2 array first, and the remaining numbers of nums1 do not need to be changed, because they have been sorted.

D. code

public void merge(int[] nums1, int m, int[] nums2, int n) {
    int pos = m-- + n-- - 1;
    while (m >= 0 && n >= 0) {
    	nums1[pos--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--];
    }
    while (n >= 0) { //如果 nums1 的数字已经复制完,把剩余的 nums2 的数字继续复制
    	nums1[pos--] = nums2[n--];
    }
}

Guess you like

Origin blog.csdn.net/weixin_51909882/article/details/123221869