1. 程式人生 > 其它 >leetcode 4 尋找兩個正序陣列的中位數

leetcode 4 尋找兩個正序陣列的中位數

給定兩個大小分別為 m 和 n 的正序(從小到大)陣列nums1 和nums2。請你找出並返回這兩個正序陣列的 中位數 。

演算法的時間複雜度應該為 O(log (m+n)) 。

示例 1:

輸入:nums1 = [1,3], nums2 = [2]
輸出:2.00000
解釋:合併陣列 = [1,2,3] ,中位數 2
示例 2:

輸入:nums1 = [1,2], nums2 = [3,4]
輸出:2.50000
解釋:合併陣列 = [1,2,3,4] ,中位數 (2 + 3) / 2 = 2.5
示例 3:

輸入:nums1 = [0,0], nums2 = [0,0]
輸出:0.00000
示例 4:

輸入:nums1 = [], nums2 = [1]
輸出:1.00000
示例 5:

輸入:nums1 = [2], nums2 = []
輸出:2.00000

提示:

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

一開始用vector存結果,但是用時過長,改為陣列後快一倍。

先比較大小,將兩個陣列的內容合併為一個。再從這個數組裡面尋找中位數,

合併的時候要注意當其中一個數組為空的情況,當其中一個為空,則直接複製另外一個數組就是結果陣列。

如果都不為空:兩個陣列的啟示索引都是0,合併一個則對應陣列索引加1。、

每次合併完需要考慮:如果其中一個數組全部合併完了,就與其中一個為空的情況一樣,直接複製另外一個數組剩下的元素。

 1 class Solution {
 2 public:
 3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
4 int len1=nums1.size(); 5 int len2=nums2.size(); 6 int res[2000]={0}; 7 int k=0; 8 if(len1==0){ 9 for(int i=0;i<len2;i++){ 10 res[k++]=nums2[i]; 11 } 12 } 13 else if(len2==0){ 14 for(int i=0;i<len1;i++){ 15 res[k++]=nums1[i]; 16 } 17 } 18 else{ 19 int t1,t2; 20 int lens=len1+len2; 21 for(int i=0,j=0;k<lens;){ 22 if(nums1[i]<=nums2[j]){ 23 res[k++]=nums1[i++]; 24 }else if(nums1[i]>nums2[j]){ 25 res[k++]=nums2[j++]; 26 } 27 if(i==len1){ 28 for(int l=j;l<len2;l++){ 29 res[k++]=nums2[l]; 30 } 31 break; 32 }else if(j==len2){ 33 for(int l=i;l<len1;l++){ 34 res[k++]=nums1[l]; 35 } 36 break; 37 } 38 } 39 } 40 int lenres=k; 41 if(lenres%2==0){ 42 double r=res[lenres/2-1]+res[(lenres/2)]; 43 return r/2.0; 44 }else{ 45 return double(res[(lenres+1)/2-1]); 46 } 47 return 0.0; 48 } 49 };