0088. Merge Sorted Array

88. Merge Sorted Array #

Problem #

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from 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]

Constraints:

  • -10^9 <= nums1[i], nums2[i] <= 10^9
  • nums1.length == m + n
  • nums2.length == n

Problem Summary #

Merge two already sorted arrays, placing the result in the first array, assuming the first array has enough space. The algorithm is required to have sufficiently low time complexity.

Solution Approach #

To avoid moving a large number of elements, start from the last position of the combined length of the two arrays, repeatedly select the larger number from the two arrays, and place it from the end of the first array toward the beginning. After just one loop, the merged array is generated.

Code #


package leetcode

func merge(nums1 []int, m int, nums2 []int, n int) {
	for p := m + n; m > 0 && n > 0; p-- {
		if nums1[m-1] <= nums2[n-1] {
			nums1[p-1] = nums2[n-1]
			n--
		} else {
			nums1[p-1] = nums1[m-1]
			m--
		}
	}
	for ; n > 0; n-- {
		nums1[n-1] = nums2[n-1]
	}
}



Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文