leetcode 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)).

You may assume nums1 and nums2 cannot be both empty.

Example 1:

  • nums1 = [1, 3]
  • nums2 = [2]
  • The median is 2.0

Example 2:

  • nums1 = [1, 2]
  • nums2 = [3, 4]
  • The median is (2 + 3)/2 = 2.5

思路:
找中位數可以等價於找第k小的數,k=(m+n)/2。
先不考慮時間複雜度,比較容易想到的就是將兩個nums合起來排序,然後輸出第k個數,k=(m+n)/2。由於兩個nums已經是分別有序,所以用兩個指針分別去遍歷這兩個數組並比較大小將較小的依次放入另外一個數組裏,時間複雜度是o(m+n)。

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    size_t n1 = nums1.size(), n2 = nums2.size();
    size_t n = n1+n2;
    vector<int> nums(n,0);

    assert(n > 0);
    
    nums1.push_back(INT_MAX);
    nums2.push_back(INT_MAX);

    size_t i = 0, j = 0, k = 0;
    while(i < n1 || j < n2) {
        if (nums1[i] <= nums2[j]) {
            nums[k++] = nums1[i++];
        }
        else
            nums[k++] = nums2[j++];
    }

    return ((n%2) ? (double)nums[(n-1)/2]:(double)(nums[(n-1)/2]+nums[n/2])/2);
        
    }
 };

要求的時間複雜度是o(log(m+n)),很容易想到用二分法。哪具體怎麼做呢?突破點在兩個數組分別有序。若數組1的第k/2個數小於數組2的第k/2個數,推出數組1的第k/2個數至多爲(k/2 + k/2 -1)大,不可能是第k小的數。也就是說第k小的數不可能出現在數組1的前k/2裏,因此可以把數組1的前k/2個數去掉。同理,若數組1的第k/2個數大於數組2的第k/2個數,去掉數組2的前k/2個數。若數組1的第k/2個數等於數組2的第k/2個數,則找到了第k小的數。

當然k/2不一定爲整數,需要處理一下。

class Solution {
    int findkthsmallest(vector<int>::iterator a, int m , vector<int>::iterator b, int n, int k)
    {
        if(m > n)
            return findkthsmallest(b, n, a, m, k);
        if(m == 0)
            return *(b+k-1);
        if(k == 1)
            return min(*a, *b);
        int pa = min(k/2, m) ;
        int pb = k - pa;
        if(*(a+pa-1) < *(b+pb-1))
            return findkthsmallest(a+pa, m - pa, b, n , k-pa);
        else if(*(a+pa-1) > *(b+pb-1))
            return findkthsmallest(a, m, b+pb, n-pb, k-pb);
        else
            return *(a+pa-1);
        
        
    }
    
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        
        vector<int>:: iterator a = nums1.begin();
        vector<int>:: iterator b = nums2.begin();
        
        int m = nums1.size();
        int n = nums2.size();
        int total = m + n ;
        if(total%2 == 1)
            return (double) findkthsmallest(a, m, b, n, total/2 + 1);
        else 
            return (double)(findkthsmallest(a, m, b, n, total/2) + findkthsmallest(a, m, b, n, total/2 +1))/2 ;
        
    }
    
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章