Leetcode 4. Median of Two Sorted Arrays (Hard) (cpp)

Leetcode 4. Median of Two Sorted Arrays (Hard) (cpp)

Tag: Binary Search, Array, Divide and Conquer

Difficulty: Hard


/*

4. Median of Two Sorted Arrays (Hard)

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

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

*/
class Solution {
public:
    double findMedianSortedArrays(vector& nums1, vector& nums2) {
        int sum = nums1.size() + nums2.size();
        double res;
        if (sum % 2) {
            res = findKth(nums1, nums2, 0, 0, sum / 2 + 1);
        } else {
            res = (findKth(nums1, nums2, 0, 0, sum / 2) + findKth(nums1, nums2, 0, 0, sum / 2 + 1)) / 2.0;
        }
        return res;
    }
private:
    double findKth(vector& nums1, vector& nums2, int s1, int s2, int k) {
        if (s1 >= nums1.size()) {
            return nums2[s2 + k - 1];
        } else if (s2 >= nums2.size()) {
            return nums1[s1 + k - 1];
        }
        if (k == 1) {
            return min(nums1[s1], nums2[s2]);
        }
        int mid1 = s1 + k / 2 - 1 >= nums1.size() ? INT_MAX : nums1[s1 + k / 2 - 1];
        int mid2 = s2 + k / 2 - 1 >= nums2.size() ? INT_MAX : nums2[s2 + k / 2 - 1];
        if (mid1 < mid2) {
            return findKth(nums1, nums2, s1 + k / 2, s2, k - k / 2);
        } else {
            return findKth(nums1, nums2, s1, s2 + k / 2, k - k / 2);
        }
    }
};

Leetcode 4. Median of Two Sorted Arrays (Hard) (cpp)_第1张图片

你可能感兴趣的:(Leetcode,C++,C++,Leetcode,Array,Leetcode,Binary,Search,Leetcode,Divide,and,Conquer)