LeetCode Problem: Merge Sorted Arrays
Problem statement:
You are given two integer arrays nums1 and nums2 (along with their respective lengths), in ascending order, your task is to merge the two arrays into one in ascending order.
The result should be stored in arr1.
Example:
Input:
nums1 = [4,1,3,5], m = 4, nums2 = [2,6], n = 2
Expected output:
nums1 = [1,2,3,4,5,6]
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/merge-sorted-array/
Golang Solution:
func merge(nums1 []int, m int, nums2 []int, n int) {
result := make([]int, m+n)
i, j, k := 0, 0, 0
for i < m && j < n {
if nums1[i] < nums2[j] {
result[k] = nums1[i]
i += 1
} else {
result[k] = nums2[j]
j += 1
}
k += 1
}
for i < m {
result[k] = nums1[i]
i += 1
k += 1
}
for j < n {
result[k] = nums2[j]
j += 1
k += 1
}
for i = 0; i < m+n; i++ {
nums1[i] = result[i]
}
}