1. Title Description

Merge nums2 into nums1 to make nums1 an ordered array. Initialize nums1 and nums2 to m and n, respectively. You can assume that nums1 has a space size equal to m + n so that it has enough space to hold elements from Nums2.

Example 1:

Input: nums1 =,2,3,0,0,0 [1], m = 3, nums2 = [6] 2, n = 3 output:,2,2,3,5,6 [1]Copy the code

Example 2:

Input: nums1 = [1], m = 1, nums2 = [], n = 0Copy the code

prompt

nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[i] <= 109
Copy the code

Second, train of thought analysis

After reading the passage, we can understand the requirements of the passage:

  • willnums1Incorporated into thenums2Cannot reopen a new array.
  • After the mergernums1It’s still an ordered array.
  • Given in example 1nums1andnums2There are2This element means that duplicate elements need to be incorporated as well.

This is a problem about arrays. It is worth noting that the problem requires that we cannot reopen an array, so we need to use the array to change itself to solve the problem

  • By arrayspliceMethods to obtainnums1The formermItems.
  • By arrayspliceMethods to obtainnums2The formernItems.
  • The arraynums2Incorporated into thenums1In the.
  • Sort the merged array in ascending order.

The code is as follows

var merge = function(nums1, m, nums2, n) { nums1.splice(m); nums2.splice(n); nums1.push(... nums2); nums1.sort((a,b)=>a-b); };Copy the code

Four,

  • This question is about how arrays change themselves, and by looking up information, I learned that, In ES6 syntax, will change the array’s own method, a total of nine, pop, respectively, a push, reverse, shift, sort, splice, unshift, copyWithin, fill, and I just know some method and usage, will learn more in the future.

  • Leetcode can use time complexity to solve the problem, but I do not have a good command of time complexity and space complexity, so I cannot give the corresponding solution. I will do it later

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign