/ * *
The title
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] example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Tip:
nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[i] <= 109
Source: LeetCode link: leetcode-cn.com/problems/me… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
The test code
Var nums1 = [1,2,3,0,0] print(nums1)
notes
The first way to think about it is to take the second array and put it in the first array and sort it
The second way to do this is to create a new array and take the smallest element from the previous two arrays and put it in the new array
The third way is not to open up the new space, just do it in the first array and take the maximum from back to front
Now let’s focus on the third way, which is sort of a three-pointer: the first index1 points to m-1, which is the valid end of the first array the first Index2 points to n-1, which is the end of the second array and the third indexCur points to m + n-1, The end of the first array containing invalid data
Indexx1 -= 1, indexx2 -= 1, indexx1 -= 1, indexx2 -= 1
Note that when you do this, if you’re taking index1, you’re going to exchange data with indexCur
The code address
Github.com/zmfflying/Z… * /
The problem solving code
import Foundation func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Var index1 = n-1 var index2 = n-1 var index2 = n-1 var indexCur = m + n-1 While indexCur >= 0 {let numIndex1 = index1 < 0? Int.min : nums1[index1] let numIndex2 = index2 < 0 ? Int. Min: nums2[index2] -= 1 if numIndex1 > numIndex2 {// if nums1[indexx2]! = numIndex1 { nums1[index1] = nums1[indexCur] nums1[indexCur] = numIndex1 } index1 -= 1 } else { nums1[indexCur] = NumIndex2 index2 -= 1} indexCur -= 1}} //func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { // var index1 = m - 1 // var index2 = n - 1 // var indexCur = m + n - 1 // // while index2 >= 0 { // if index1 >= 0 && nums1[index1] > nums2[index2] { // nums1[indexCur] = nums1[index1] // index1 -= 1 // } else { // nums1[indexCur] = nums2[index2] // index2 -= 1 // } // indexCur -= 1 // } //}Copy the code