LeetCode Median of Two Sorted Arrays Binary Search (golang)

该问题要求在O(log(m+n))的时间复杂度内找到两个有序数组的中位数。通过定义中位数,转化为寻找两个数组中的第k小元素。通过比较A和B数组的第k/2-1个元素,进行二分查找排除部分元素。考虑特殊情形,如数组为空或k等于1的情况。文章提供了Golang代码实现。
摘要由CSDN通过智能技术生成

Problem
在这里插入图片描述
Analysis Process

The problem says there are two arrays and the overall run time complexity should be O(log(m+n)),it’s natural to think about merging arrays and binary search.

By the definition of median, when m+n is odd,the median is the (m+n)/2 element in two ordered arrays.when m+n is even,median is the (m+n)/2 and (m+n)/2+1 element in two ordered arrays
So, this problem translates to looking for the k smallest number in two ordered arrays

Suppose the two ordered arrays are A and B
1.If A[k/2−1]<B[k/2−1],the only numbers that are less than A[k/2−1] are the first k/2−1 of A and the first k/2−1 of B.So,A[k/2−1] can’t be the k element,rule out A[0] to A[k/2−1]
2.If A[k/2−1]>B[k/2−1],rule out B[0] to B[k/2−1]
3.If A[k/2−1]=B[k/2−1],same as the first case

Consider the following special cases
1.f A[k/2−1] or B[k/2−1] cross the line ,pick the last element in the corresponding array
2. If an array is empty, all elements in the array are excluded, and we can simply return the k smallest element in another array
3. If k=1, we just return the minimum value of the first element of both arrays

Code

func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
   
	Length := len
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值