Median of Two Sorted Arrays
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)).
可以用归并,但O(m+n),要求O(log(m+n)),因此转化为求前k的值,若a[k/2-1]<b[k/2-1],则a[0]-a[k/2-1]都在前k里,因此去除,继续递归。
3种边界:(1)m=0(m为较小数组);(2)k=1;(3)a[k/2-1]==b[k/2-1];
PS:注意判断条件,开始因为if(k=1)导致一直出错又找不出错误。
1 class Solution { 2 private: 3 double findkth(vector<int>::iterator nums1, int m, vector<int>::iterator nums2, int n, int k) 4 { 5 if(m>n) 6 return findkth(nums2,n,nums1,m,k); 7 if(m==0) 8 return *(nums2+k-1); 9 if(k==1) 10 return min(*nums1,*nums2); 11 int tmpm=min(m,k/2); 12 int tmpn=k-tmpm; 13 if(*(nums1+tmpm-1)<*(nums2+tmpn-1)) 14 { 15 16 return findkth(nums1+tmpm,m-tmpm,nums2,n,k-tmpm); 17 } 18 else if(nums1[tmpm-1]>nums2[tmpn-1]) 19 { 20 21 return findkth(nums1,m,nums2+tmpn,n-tmpn,k-tmpn); 22 } 23 else 24 return *(nums1+tmpm-1); 25 } 26 public: 27 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { 28 int m=nums1.size(); 29 int n=nums2.size(); 30 int total=m+n; 31 vector<int>::iterator it1=nums1.begin(); 32 vector<int>::iterator it2=nums2.begin(); 33 if(total&0x1) 34 return findkth(it1,m,it2,n,total/2+1); 35 else 36 return double (findkth(it1,m,it2,n,total/2)+findkth(it1,m,it2,n,total/2+1))*1.0/2; 37 } 38 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了