Topic describes
Their thinking
- First, use the splice method to remove extraneous elements after nums1 and nums2.
- If either of them is an empty array, it is pushed directly into nums1.
- Define double Pointers and compare them in sequence, placing the smaller ones in nums1.
- Determine the situation in which the left and right Pointers go first.
AC code
var merge = function(nums1, m, nums2, n) {
nums1.splice(m)
nums2.splice(n)
if (nums1.length === 0 || nums2.length === 0) { nums1.push(... nums2);return;
}
// Define the left pointer
let left = 0;
// Define the right pointer
let right = 0;
// Define the final result array
let result = [];
// When neither side has reached the end
while(left ! = nums1.length && right ! = nums2.length) {if (nums1[left] <= nums2[right]) {
left++;
} else {
nums1.splice(left,0,nums2[right])
right++
}
}
// If the left pointer has reached the end, but the right pointer has not
if(left === nums1.length && right ! = nums2.length) { nums1.push(... nums2.slice(right)); }// If the right pointer has reached the end, but the left pointer has not
if(right === nums1.length && left ! = nums2.length) { nums1.push(... nums1.slice(left)); }};Copy the code
The title to reflect
- Learn to add elements using the splice method.
- Note that it is required to sort in place, so assigning a parameter directly will not pass the test.
- Learn to use double Pointers.