1. 程式人生 > 實用技巧 >七夕祭

七夕祭

Given two sorted arrays nums1 and nums2 of size m and n respectively.

Return the median of the two sorted arrays.

Follow up: The overall run time complexity should be O(log (m+n)).

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:

Input: nums1 = [1,2], nums2 = [3,4]

Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Example 3:

Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.00000
Example 4:

Input: nums1 = [], nums2 = [1]
Output: 1.00000
Example 5:

Input: nums1 = [2], nums2 = []
Output: 2.00000

Constraints:

nums1,length == m
nums2,length == n
0 <= m <= 1000
0 <= n <= 1000

1 <= m + n <= 2000

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int n=nums1.size();
        int m=nums2.size();
        if(n>m)
        {
            return findMedianSortedArrays(nums2,nums1);
            //為了便於編碼,保證nums1是長度小的陣列
} int LMax1,LMax2,RMin1,RMin2;//分界處的點 int c1,c2;//nums1,nums2左半段的長度 int left=0,right=2*n; //加上虛擬的'#',nums1的長度為2*n+1; //例子:#1#4#7#9# #2#3#8# //虛擬之後,LMaxi = (Ci-1)/2 位置上的元素 //RMini = Ci/2 位置上的元素 while(left <= right)//二分 { c1=(left+right)/2; c2 = m+n-c1; LMax1 = (c1 == 0) ? INT_MIN : nums1[(c1-1)/2]; RMin1 = (c1 == 2*n) ? INT_MAX :nums1[c1/2]; LMax2 = (c2 == 0) ? INT_MIN : nums2[(c2-1)/2]; RMin2 = (c2 == 2*m)? INT_MAX :nums2[c2/2]; if(LMax1 > RMin2) right = c1-1; else if(LMax2 >RMin1) left = c1+1; else break;//都滿足的話則找到了 } return (max(LMax1,LMax2)+min(RMin1,RMin2))/2.0; } };

注意:1.log(m+n)則限定為二分查詢的方式實現 2.劃分界限,找到中位數 3.加入虛擬的"#",來實現奇數和偶數的討論