2013.12.1 19:29
There are two sorted arrays A and B 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)).
Solution:
Given two sorted array, find out the median of all elements. My solution is straightforward, merge two arrays and return the median.
Time complexity is O(m + n), space complexity O(m + n) as well. In-place merge is too much trouble, and merging by swapping have some bad case of O(n^2) time compleity. So the direct solution is sometimes a wise solution at all :)
Here is the accepted code.
Accepted code:
1 // 1RE 1AC 2 class Solution { 3 public: 4 double findMedianSortedArrays(int A[], int m, int B[], int n) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 merge(A, m, B, n); 8 if((m + n) % 2 == 1){ 9 return C[(m + n - 1) / 2]; 10 }else{ 11 return (C[(m + n) / 2 - 1] + C[(m + n) / 2]) / 2.0; 12 } 13 } 14 private: 15 vector<int> C; 16 17 void merge(int A[], int m, int B[], int n) { 18 C.clear(); 19 20 int i, j; 21 22 i = j = 0; // Bugged here, omitted this sentence 23 while(i < m && j < n){ 24 if(A[i] <= B[j]){ 25 C.push_back(A[i++]); 26 }else{ 27 C.push_back(B[j++]); 28 } 29 } 30 31 while(i < m){ 32 C.push_back(A[i++]); 33 } 34 35 while(j < n){ 36 C.push_back(B[j++]); 37 } 38 } 39 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)