NOTE
Median of Two Sorted Arrays
LeetCode notes on finding the median of two sorted arrays by merging them.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given two sorted arrays nums1 and nums2 of sizes m and n, find and return the median of the two sorted arrays.
2. Approach
- Approach 1
- Merge the arrays in sorted order, then take the middle value
3. Implementation
3.1. Merge
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
nums := make([]int, len(nums1)+len(nums2))
i := 0
j := 0
k := 0
for i < len(nums1) && j < len(nums2) {
if nums1[i] < nums2[j] {
nums[k] = nums1[i]
i++
} else {
nums[k] = nums2[j]
j++
}
k++
}
for i < len(nums1) {
nums[k] = nums1[i]
k++
i++
}
for j < len(nums2) {
nums[k] = nums2[j]
k++
j++
}
if len(nums) %2 != 0 {
return float64(nums[len(nums)/2])
}else {
return float64(nums[len(nums)/2-1] + nums[len(nums)/2]) / 2.0
}
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub