Skip to content

Instantly share code, notes, and snippets.

@nhatlee
Created August 19, 2024 04:03
Show Gist options
  • Save nhatlee/35c8404f2a2358c06a4fa0840fda7e2d to your computer and use it in GitHub Desktop.
Save nhatlee/35c8404f2a2358c06a4fa0840fda7e2d to your computer and use it in GitHub Desktop.
Merge Sorted Array
/// https://leetcode.com/problems/merge-sorted-array/description/?envType=study-plan-v2&envId=top-interview-150
/// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
/// Output: [1,2,2,3,5,6]
///
///
func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
var lastIdx = m + n - 1
var mPointer = m
var nPointer = n
while mPointer > 0 && nPointer > 0 {
if nums1[mPointer - 1] > nums2[nPointer - 1] {
nums1[lastIdx] = nums1[mPointer - 1]
mPointer -= 1
} else {
nums1[lastIdx] = nums2[nPointer - 1]
nPointer -= 1
}
lastIdx -= 1
}
while nPointer > 0 {
nums1[lastIdx] = nums2[nPointer - 1]
nPointer -= 1
lastIdx -= 1
}
}
/// Test cases
var num1 = [1,2,3,0,0,0, 0, 0, 0]
merge(&num1, 3, [2,5,6,7, 8, 9], 6)
print(num1)
var num2 = [2,2,3,0,0,0]
merge(&num2, 3, [1,2,2], 3)
print(num2)
var num3 = [2,3,0,0,0]
merge(&num3, 2, [1,2,4], 3)
print(num3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment