leetcode--Median of Two Sorted Arrays
生活随笔
收集整理的這篇文章主要介紹了
leetcode--Median of Two Sorted Arrays
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.題目描述
2.解法分析 我本來直接想用二分法求出結果,然后有了下面這個結果,結果發現當m+n為偶數時計算出來的結果不對,因為我最初的算法就是求中位數,而不是題目要求的兩個中位數的平均值。
| 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)). |
| class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function unordered_set<int> myHash; vector<int>::iterator iter; vector<int> result; result.assign(2,0); if(target%2==0) { int count=0; for(int i=0;i<numbers.size();++i) { if(numbers[i]==target/2) { if(count==0){result[0]=i+1;count++; } else { result[1]=i+1;return result; } } } } for(iter=numbers.begin();iter!=numbers.end();++iter) { myHash.insert(*iter); } for(int i=0;i<numbers.size();++i) { myHash.erase(numbers[i]); if(myHash.count(target-numbers[i])==1) { result[0]=i+1;break; } myHash.insert(numbers[i]); } for(int i=result[0];i<numbers.size();++i) { if((numbers[result[0]-1]+numbers[i])==target) { result[1]=i+1;break; } } return result; } }; |
?
本來想修修補補,看看能不能夠AC,結果弄了好半天煩死了,因此覺得應該會有比較統一的方法。結果搜尋到了一個很統一的方法,這個方法將找兩個數組的中位數推廣到了找兩個數組中第k大的數字,有了這個思路代碼就很簡單了。
| class Solution { //more detail refer to: http://fisherlei.blogspot.com/2012/12/leetcode-median-of-two-sorted-arrays.html //using the method of getting the kth number in the two sorted array to solve the median problem //divide-and-conquer //very clean and concise public: double findMedianSortedArrays(int A[], int m, int B[], int n) { if((n+m)%2 ==0) { return (GetMedian(A,m,B,n, (m+n)/2) + GetMedian(A,m,B,n, (m+n)/2+1))/2.0; } else return GetMedian(A,m,B,n, (m+n)/2+1); } int GetMedian(int a[], int n, int b[], int m, int k)//get the kth number in the two sorted array { //assert(a && b); if (n <= 0) return b[k-1]; if (m <= 0) return a[k-1]; if (k <= 1) return min(a[0], b[0]); //a: section1 section2 //b: section3 section4 if (b[m/2] >= a[n/2]) { if ((n/2 + 1 + m/2) >= k) return GetMedian(a, n, b, m/2, k);//abort section 4 else return GetMedian(a + n/2 + 1, n - (n/2 + 1), b, m, k - (n/2 + 1)); //abort section 1 } else { if ((m/2 + 1 + n/2) >= k) return GetMedian( a, n/2,b, m, k);//abort section 2 else return GetMedian( a, n, b + m/2 + 1, m - (m/2 + 1),k - (m/2 + 1));//abort section 3 } } }; |
轉載于:https://www.cnblogs.com/obama/p/3267037.html
總結
以上是生活随笔為你收集整理的leetcode--Median of Two Sorted Arrays的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 杭电 汉诺塔问题总结
- 下一篇: 上拉电阻下拉电阻高阻态