There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
一开始写的可惜出错,边界情况判断不清,这并不是一个简单的问题。
先来一个比较无脑的ruby黑魔法
def find_median_sorted_arrays(a, b)
c = (a + b).sort
mid = c.size/2
( c.size.odd?) ? c[mid] : ((c[mid]+c[mid-1]).to_f/2)
end
下面是分治法,速度会快一点
def find_median_sorted_arrays(a,b)
len=a.size+b.size
return find_kth(a,b,len/2+1) if len.odd?
(find_kth(a,b,len/2)+find_kth(a,b,len/2+1))*0.5
end
## k>0
def find_kth(a,b,k)
return find_kth(b,a,k) if a.size<b.size #ensure a.size >= b.size
return a[k-1] if b.size==0
return a[0]>b[0] ? b[0] : a[0] if k==1
lenb=[b.size,k/2].min
lena=k-lenb
return find_kth(a[lena..-1],b,k-lena) if a[lena-1]<b[lenb-1]
find_kth(a,b[lenb..-1],k-lenb)
end
网友评论